Author SHA1 Message Date
Christian Manivong 62bbc7df49 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.
2026-12-01 12:47:25 +01:00
14 changed files with 725 additions and 930 deletions

No files matched your search

+9 -11
View File
@@ -7,17 +7,15 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- Disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896), through
napalm-device-types' `HostStorageMixin`, so the host stays a host. `get_disks` reads
`Get-PhysicalDisk` (model, serial, medium, NVMe, Windows' health, the Storage Spaces
pool a disk is in); `get_disk_smart` reads `Get-StorageReliabilityCounter` per disk
(temperature, wear, power-on hours, uncorrected read and write errors);
`get_disk_pools` reads Storage Spaces' pools; `get_volumes` the fixed volumes mounted at
a drive letter or in a folder, with file system and health. A disk whose counter cannot
be read -- the cmdlet needs an administrator, and virtual disks often have none -- has
no drive health rather than an error; a virtual disk or a RAID controller's logical
disk reads temperature -1 and health "unknown" instead of zeros and a "healthy" nobody
measured. A Storage Spaces virtual disk is not listed as a physical disk.
- 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
+27 -24
View File
@@ -42,8 +42,8 @@ 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* |
| `get_disks` / `get_disk_smart` / `get_disk_pools` / `get_volumes` | `Get-PhysicalDisk`, `Get-StorageReliabilityCounter`, `Get-StoragePool -IsPrimordial $false`, `Get-Volume` + `Get-Partition`; no smartctl. See *Storage* |
`running_kernel` carries the full build including the update revision
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
@@ -98,32 +98,35 @@ 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.
### Storage
### Security posture
napalm-device-types' `HostStorageMixin` (NetOrk/netork#2896): the host's storage without
the storage role, so the driver stays a host. Nothing is installed; everything comes from
the Storage module's CIM classes.
`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.
* **Disks** are `Get-PhysicalDisk` (`PhysicalDisk<N>` by `DeviceId`): model, serial,
medium, bus (NVMe is its own type), Windows' `HealthStatus` (`Healthy`, `Warning`,
`Unhealthy` -> `healthy`, `warning`, `failed`) and, for disks in a Storage Spaces pool,
the pool. A Storage Spaces virtual disk is no physical disk and is not listed.
* **Drive health** (`get_disk_smart`) is `Get-StorageReliabilityCounter` per disk:
temperature and its highest, wear (`percentage_used`, not for spinning disks), power-on
hours, uncorrected read and write errors. It needs an administrator; a disk whose
counter cannot be read, or whose counters are all empty, has no drive health and is
left out. Windows writes `0` for a temperature it does not have, which reads as none.
* **Unknown is not healthy.** A disk whose medium Windows cannot tell and whose counters
are empty -- a virtual disk, a RAID controller's logical disk -- reads temperature `-1`
and health `unknown`: Windows calls it `Healthy`, which only says it is attached.
`Warning` and `Unhealthy` are always passed on.
* **Pools** are Storage Spaces (`storage-spaces`; `Simple`, `Mirror`, `Parity` ->
`stripe`, `mirror`, `parity`). Size and allocation are raw capacity.
* **Volumes** are the fixed volumes mounted at a drive letter (`C:`) or in a folder
(`C:\Logs`), with file system and health; the EFI and recovery partitions are mounted
nowhere and left out.
* **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`, ...).
A host without the Storage module reads as having none; an empty answer raises.
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.
+353
View File
@@ -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)
-355
View File
@@ -1,355 +0,0 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
:class:`WindowsStorageMixin` implements napalm-device-types'
:class:`~napalm_device_types.host_storage.HostStorageMixin` for the driver, which carries
each script across ``PsrpTransport.run``. A Windows host has disks; it is not a storage
device, so the getters come with no role and the driver stays ``windows``.
Everything is read from the Storage module's CIM classes, the same on every Windows
Server 2016+ and Windows 10/11, without installing anything:
- **Disks** are ``Get-PhysicalDisk``: model, serial, medium (``MediaType``), bus
(``BusType``; NVMe is a type of its own) and Windows' verdict (``HealthStatus``). A
Storage Spaces virtual disk (``BusType`` ``Spaces``) is built from other disks and is no
physical disk; its members are. Which pool a disk belongs to is
``Get-StoragePool -IsPrimordial $false`` with its member disks.
- **Drive health** is ``Get-StorageReliabilityCounter`` per disk: temperature, wear,
power-on hours, uncorrected read and write errors. It needs an administrator, and a
virtual disk often has none: a disk whose counter cannot be read has no counter, which
is "unknown", not an error. Windows writes ``0`` where a drive does not report a value,
so a zero temperature is none, and a disk whose counters are all empty reports nothing.
- **Health without a measurement is "unknown".** A disk whose medium Windows cannot tell
(``MediaType`` ``Unspecified``) and whose counters are empty is a virtual disk or a RAID
controller's logical disk; Windows calls it ``Healthy``, which says it is attached, not
that a drive is well. Its health reads ``unknown``. ``Warning`` and ``Unhealthy`` are
always passed on.
- **Pools** are Storage Spaces' ``Get-StoragePool -IsPrimordial $false``. Their size and
allocation are raw capacity: what is usable depends on each virtual disk's resiliency.
- **Volumes** are ``Get-Volume``'s fixed volumes, mounted at a drive letter or in a
folder (``Get-Partition``'s ``AccessPaths``). A volume mounted nowhere -- the EFI system
partition, the recovery partition -- is left out.
Each script asks ``Get-Command`` first, so a host without the Storage module answers "not
supported" (empty) rather than failing. Drive health is read with the disks, in one round
trip; ``get_disks`` and ``get_disk_smart`` each send it.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from napalm_device_types.host_storage import DiskSmartDict, HostStorageMixin, HostVolumeDict
from napalm_device_types.models import DiskPoolDict, LogicalVolumeDict, PhysicalDiskDict
from napalm_windows._powershell import _as_list
_PS_DISKS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-PhysicalDisk -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$readCounters = [bool](
Get-Command -Name Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
)
$pools = @{}
if (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue) {
try {
foreach ($pool in @(Get-StoragePool -IsPrimordial $false)) {
foreach ($member in @(Get-PhysicalDisk -StoragePool $pool)) {
$pools[[string]$member.UniqueId] = [string]$pool.FriendlyName
}
}
} catch { }
}
$disks = @(Get-PhysicalDisk | ForEach-Object {
$disk = $_
$counter = $null
if ($readCounters) {
try { $counter = $disk | Get-StorageReliabilityCounter } catch { $counter = $null }
}
[pscustomobject]@{
device_id = [string]$disk.DeviceId
unique_id = [string]$disk.UniqueId
name = [string]$disk.FriendlyName
model = [string]$disk.Model
vendor = [string]$disk.Manufacturer
serial = [string]$disk.SerialNumber
media_type = [string]$disk.MediaType
bus_type = [string]$disk.BusType
health = [string]$disk.HealthStatus
size = $disk.Size
spindle = $disk.SpindleSpeed
pool = $pools[[string]$disk.UniqueId]
counter = if ($counter) {
[pscustomobject]@{
temperature = $counter.Temperature
temperature_max = $counter.TemperatureMax
wear = $counter.Wear
power_on_hours = $counter.PowerOnHours
read_errors_uncorrected = $counter.ReadErrorsUncorrected
write_errors_uncorrected = $counter.WriteErrorsUncorrected
}
} else { $null }
}
})
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
counters = $readCounters
disks = $disks
})
"""
_PS_STORAGE_POOLS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
pools = @(Get-StoragePool -IsPrimordial $false | ForEach-Object {
$pool = $_
[pscustomobject]@{
name = [string]$pool.FriendlyName
health = [string]$pool.HealthStatus
operational = @($pool.OperationalStatus | ForEach-Object { [string]$_ })
size = $pool.Size
allocated = $pool.AllocatedSize
resiliency = [string]$pool.ResiliencySettingNameDefault
read_only = [bool]$pool.IsReadOnly
disks = @(Get-PhysicalDisk -StoragePool $pool | ForEach-Object {
[pscustomobject]@{
device_id = [string]$_.DeviceId
unique_id = [string]$_.UniqueId
}
})
}
})
})
"""
_PS_VOLUMES = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-Volume -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$mounts = @{}
try {
foreach ($partition in @(Get-Partition)) {
$paths = @($partition.AccessPaths | Where-Object { $_ })
$folders = @($paths | Where-Object { $_ -notlike '\\?\*' })
foreach ($path in @($paths | Where-Object { $_ -like '\\?\Volume*' })) {
$mounts[$path] = $folders
}
}
} catch { }
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
volumes = @(Get-Volume | Where-Object { [string]$_.DriveType -eq 'Fixed' } | ForEach-Object {
$volume = $_
[pscustomobject]@{
letter = [string]$volume.DriveLetter
label = [string]$volume.FileSystemLabel
file_system = [string]$volume.FileSystem
size = $volume.Size
remaining = $volume.SizeRemaining
health = [string]$volume.HealthStatus
path = [string]$volume.Path
mounts = @($mounts[[string]$volume.Path])
}
})
})
"""
#: ``HealthStatus`` as the contract says it; anything else is "unknown".
_HEALTH = {"healthy": "healthy", "warning": "warning", "unhealthy": "failed"}
#: The same verdict in drive-health terms.
_DRIVE_HEALTH = {"healthy": "ok", "warning": "warning", "unhealthy": "failed"}
_MEDIA = {"hdd": "hdd", "ssd": "ssd", "scm": "ssd"}
_POOL_STATUS = {"healthy": "online", "warning": "degraded", "unhealthy": "faulted"}
_LEVELS = {"simple": "stripe", "mirror": "mirror", "parity": "parity"}
#: Buses of a disk built from other disks, not a drive.
_VIRTUAL_BUSES = frozenset({"spaces", "storage spaces"})
#: ``SpindleSpeed`` when Windows does not know it.
_UNKNOWN_SPEED = 0xFFFFFFFF
def _text(value: Any) -> str:
return str(value or "").strip()
def _number(value: Any) -> int | None:
"""A counter's value; ``None`` when the drive does not report it."""
return None if value is None else int(value)
def _positive(value: Any) -> int | None:
"""A value Windows writes as ``0`` when it has none (a temperature)."""
number = _number(value)
return number if number else None
def _slot(device_id: Any, unique_id: Any) -> str:
"""``PhysicalDisk<N>``, as ``Get-PhysicalDisk`` names a disk; its id when it has no number."""
number = _text(device_id)
return f"PhysicalDisk{number}" if number else _text(unique_id)
class _Disk:
"""One disk of ``_PS_DISKS``."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = raw
self.slot = _slot(raw.get("device_id"), raw.get("unique_id"))
self.counter: dict[str, Any] = raw.get("counter") or {}
self.reports = any(value for value in self.counter.values())
bus = _text(raw.get("bus_type")).lower()
media = _MEDIA.get(_text(raw.get("media_type")).lower(), "unknown")
self.type = "nvme" if bus == "nvme" else media
self.is_physical = bus not in _VIRTUAL_BUSES
self.status = _text(raw.get("health")).lower()
def health(self) -> str:
verdict = _HEALTH.get(self.status, "unknown")
if verdict == "healthy" and self.type == "unknown" and not self.reports:
return "unknown"
return verdict
def disk(self) -> PhysicalDiskDict:
spindle = int(self.raw.get("spindle") or 0)
return {
"slot": self.slot,
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"vendor": _text(self.raw.get("vendor")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"rpm": spindle if spindle != _UNKNOWN_SPEED else 0,
"temperature": _positive(self.counter.get("temperature")) or -1,
"health": self.health(),
"pool": _text(self.raw.get("pool")),
}
def smart(self) -> DiskSmartDict:
c = self.counter
return {
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"health": _DRIVE_HEALTH.get(self.status, "unknown"),
"wearout": None,
"temperature": _positive(c.get("temperature")),
# A spinning disk does not wear out by writes; its Wear is no reading.
"percentage_used": None if self.type == "hdd" else _number(c.get("wear")),
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": _number(c.get("power_on_hours")),
"temperature_max": _positive(c.get("temperature_max")),
"read_errors_uncorrected": _number(c.get("read_errors_uncorrected")),
"write_errors_uncorrected": _number(c.get("write_errors_uncorrected")),
}
def _pool(raw: dict[str, Any]) -> DiskPoolDict:
total, used = int(raw.get("size") or 0), int(raw.get("allocated") or 0)
resiliency = _text(raw.get("resiliency")).lower()
return {
"name": _text(raw.get("name")),
"type": "storage-spaces",
"level": _LEVELS.get(resiliency, resiliency or "unknown"),
"status": _POOL_STATUS.get(_text(raw.get("health")).lower(), "unknown"),
"total": total,
"used": used,
"available": max(total - used, 0),
"disks": [
_slot(d.get("device_id"), d.get("unique_id")) for d in _as_list(raw.get("disks"))
],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
def _mount(raw: dict[str, Any]) -> tuple[str, str] | None:
"""The volume's key and mount point: its drive letter, else the first folder it is
mounted in; None when it is mounted nowhere."""
letter = _text(raw.get("letter")).split("\x00", 1)[0]
if letter:
return f"{letter}:", f"{letter}:\\"
folders = [_text(m) for m in _as_list(raw.get("mounts")) if _text(m)]
if not folders:
return None
return folders[0].rstrip("\\"), folders[0]
def _volume(raw: dict[str, Any], key: str, mountpoint: str) -> HostVolumeDict:
total, available = int(raw.get("size") or 0), int(raw.get("remaining") or 0)
return {
"name": _text(raw.get("label")) or key,
"pool": "",
"type": "filesystem",
"total": total,
"used": max(total - available, 0),
"available": available,
"mountpoint": mountpoint,
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": _text(raw.get("file_system")),
"health": _HEALTH.get(_text(raw.get("health")).lower(), "unknown"),
}
class WindowsStorageMixin(HostStorageMixin):
"""The Storage module's disks, pools, volumes and reliability counters."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _storage_read(self, script: str, what: str) -> dict[str, Any] | None:
"""The script's answer; None when the host has no Storage module.
:raises ValueError: when the reading came back empty -- it could not look.
"""
out = self._run_raw(script).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 if raw.get("supported") else None
def _disks(self) -> list[_Disk]:
raw = self._storage_read(_PS_DISKS, "disk")
if raw is None:
return []
disks = (_Disk(d) for d in _as_list(raw.get("disks")))
return [d for d in disks if d.is_physical]
def get_disks(self) -> list[PhysicalDiskDict]:
"""``Get-PhysicalDisk`` with each disk's temperature; see the module."""
return [d.disk() for d in self._disks()]
def get_disk_smart(self) -> dict[str, DiskSmartDict]:
"""``Get-StorageReliabilityCounter`` per disk; disks that report nothing are left out."""
return {d.slot: d.smart() for d in self._disks() if d.reports}
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
"""Storage Spaces' pools; ``{}`` on a host without any."""
raw = self._storage_read(_PS_STORAGE_POOLS, "storage pool")
pools = [_pool(p) for p in _as_list((raw or {}).get("pools"))]
return {p["name"]: p for p in pools}
def get_volumes(self) -> dict[str, LogicalVolumeDict]:
"""``Get-Volume``'s fixed volumes that are mounted somewhere, keyed by where."""
raw = self._storage_read(_PS_VOLUMES, "volume")
volumes: dict[str, LogicalVolumeDict] = {}
for entry in _as_list((raw or {}).get("volumes")):
mount = _mount(entry)
if mount is not None:
volumes[mount[0]] = _volume(entry, *mount)
return volumes
+2 -2
View File
@@ -27,8 +27,8 @@ 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.storage import WindowsStorageMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
@@ -262,7 +262,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsStorageMixin, OSDriver):
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsPostureMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
-102
View File
@@ -1,102 +0,0 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "eui.0025385A11B22C33",
"name": "Samsung SSD 980 PRO 1TB",
"model": "Samsung SSD 980 PRO 1TB",
"vendor": "",
"serial": "0025_385A_11B2_2C33.",
"media_type": "SSD",
"bus_type": "NVMe",
"health": "Healthy",
"size": 1000204886016,
"spindle": 0,
"pool": null,
"counter": {
"temperature": 41,
"temperature_max": 68,
"wear": 3,
"power_on_hours": 5120,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
},
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": " WD-WCC7K1ABCDEF",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Warning",
"size": 4000787030016,
"spindle": 5400,
"pool": "Pool1",
"counter": {
"temperature": 36,
"temperature_max": 51,
"wear": 0,
"power_on_hours": 31012,
"read_errors_uncorrected": 12,
"write_errors_uncorrected": 0
}
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": "WD-WCC7K1ABCDF0",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Healthy",
"size": 4000787030016,
"spindle": 4294967295,
"pool": "Pool1",
"counter": {
"temperature": 0,
"temperature_max": null,
"wear": 0,
"power_on_hours": 30990,
"read_errors_uncorrected": null,
"write_errors_uncorrected": null
}
},
{
"device_id": "4",
"unique_id": "600508B1001C5A6B7C8D9E0F1A2B3C4D",
"name": "HPE LOGICAL VOLUME",
"model": "LOGICAL VOLUME",
"vendor": "HPE",
"serial": "PDNLH0BRH9A1B2",
"media_type": "Unspecified",
"bus_type": "RAID",
"health": "Healthy",
"size": 1200210141184,
"spindle": 4294967295,
"pool": null,
"counter": null
},
{
"device_id": "",
"unique_id": "{6b2f0c1e-0b5a-4a5e-9d3f-1c2b3a4d5e6f}",
"name": "Data",
"model": "Storage Space",
"vendor": "Microsoft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "Spaces",
"health": "Healthy",
"size": 2199023255552,
"spindle": 0,
"pool": null,
"counter": null
}
]
}
-28
View File
@@ -1,28 +0,0 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "60022480A1B2C3D4E5F60718293A4B5C",
"name": "Msft Virtual Disk",
"model": "Virtual Disk",
"vendor": "Msft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "SAS",
"health": "Healthy",
"size": 136365211648,
"spindle": 4294967295,
"pool": null,
"counter": {
"temperature": 0,
"temperature_max": 0,
"wear": 0,
"power_on_hours": null,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
}
]
}
+1
View File
@@ -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":{}}
+1
View File
@@ -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":{}}
-26
View File
@@ -1,26 +0,0 @@
{
"supported": true,
"pools": [
{
"name": "Pool1",
"health": "Warning",
"operational": [
"Degraded"
],
"size": 8001574060032,
"allocated": 2199023255552,
"resiliency": "Mirror",
"read_only": false,
"disks": [
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4"
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5"
}
]
}
]
}
-61
View File
@@ -1,61 +0,0 @@
{
"supported": true,
"volumes": [
{
"letter": "C",
"label": "",
"file_system": "NTFS",
"size": 999483936768,
"remaining": 712345698304,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-100000000000}\\",
"mounts": [
"C:\\"
]
},
{
"letter": "D",
"label": "Data",
"file_system": "ReFS",
"size": 2196875771904,
"remaining": 109521666048,
"health": "Warning",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-200000000000}\\",
"mounts": [
"D:\\"
]
},
{
"letter": "",
"label": "Logs",
"file_system": "NTFS",
"size": 1200191766528,
"remaining": 1100000000000,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-300000000000}\\",
"mounts": [
"C:\\Logs\\"
]
},
{
"letter": "",
"label": "",
"file_system": "FAT32",
"size": 104857600,
"remaining": 71303168,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-400000000000}\\",
"mounts": []
},
{
"letter": "",
"label": "",
"file_system": "NTFS",
"size": 681574400,
"remaining": 98566144,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-500000000000}\\",
"mounts": []
}
]
}
+330
View File
@@ -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))
-317
View File
@@ -1,317 +0,0 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
Each reading is one script whose JSON a fake host answers from
tests/fixtures/synthetic/: ``disks_server.json`` (an NVMe SSD, two SATA disks in a
Storage Spaces pool, a RAID controller's logical disk and a Storage Spaces virtual
disk), ``disks_vm.json`` (a Hyper-V guest's virtual disk with empty reliability
counters), ``storage_pools.json`` and ``volumes.json``.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import HostStorageMixin, OSDriver
from napalm_device_types.roles import primary_role_of, role_keys_of
from napalm_windows import WindowsDriver
from napalm_windows import storage as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
def _load(name: str) -> Any:
return json.loads((FIXTURES / name).read_text())
class FakeHost:
"""Answers each storage script with *answers*' entry for it."""
def __init__(self, answers: dict[str, Any]) -> None:
self.answers = answers
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
answer = self.answers[script]
return answer if isinstance(answer, str) else json.dumps(answer)
def close(self) -> None:
self.is_open = False
def _driver(**answers: Any) -> WindowsDriver:
scripts = {
"disks": mod._PS_DISKS,
"pools": mod._PS_STORAGE_POOLS,
"volumes": mod._PS_VOLUMES,
}
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeHost({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
return d
def _server() -> WindowsDriver:
return _driver(
disks=_load("disks_server.json"),
pools=_load("storage_pools.json"),
volumes=_load("volumes.json"),
)
# ---------------------------------------------------------------------------
# The contract
# ---------------------------------------------------------------------------
class TestContract:
def test_a_host_with_storage_stays_a_host(self):
assert issubclass(WindowsDriver, HostStorageMixin)
assert "storage" not in role_keys_of(WindowsDriver)
assert primary_role_of(WindowsDriver) == primary_role_of(OSDriver)
def test_every_getter_is_there(self):
for name in ("get_disks", "get_disk_pools", "get_volumes", "get_disk_smart"):
assert callable(getattr(WindowsDriver, name)), name
@pytest.mark.parametrize("script", ["_PS_DISKS", "_PS_STORAGE_POOLS", "_PS_VOLUMES"])
def test_scripts_follow_the_driver_conventions(self, script):
text = getattr(mod, script)
assert "$ErrorActionPreference = 'Stop'" in text
assert "ConvertTo-Json" in text
assert "Get-Command" in text # a missing cmdlet is "not supported", not an error
def test_counters_are_read_per_disk_and_may_fail(self):
"""Get-StorageReliabilityCounter needs an administrator and is missing on some
virtual disks: one disk's failure is that disk's missing counter."""
assert "try { $counter = $disk | Get-StorageReliabilityCounter }" in mod._PS_DISKS
assert "catch { $counter = $null }" in mod._PS_DISKS
def test_no_smartctl(self):
for script in (mod._PS_DISKS, mod._PS_STORAGE_POOLS, mod._PS_VOLUMES):
assert "smartctl" not in script
# ---------------------------------------------------------------------------
# get_disks
# ---------------------------------------------------------------------------
class TestDisks:
def test_an_nvme_ssd(self):
disk = _server().get_disks()[0]
assert disk == {
"slot": "PhysicalDisk0",
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"vendor": "",
"type": "nvme",
"size": 1000204886016,
"rpm": 0,
"temperature": 41,
"health": "healthy",
"pool": "",
}
def test_a_pool_member_with_a_warning(self):
disk = _server().get_disks()[1]
assert disk["slot"] == "PhysicalDisk1"
assert disk["serial"] == "WD-WCC7K1ABCDEF" # ATA serials come padded
assert (disk["type"], disk["rpm"], disk["temperature"]) == ("hdd", 5400, 36)
assert (disk["health"], disk["pool"]) == ("warning", "Pool1")
def test_a_zero_temperature_and_an_unknown_speed_are_unknown(self):
disk = _server().get_disks()[2]
assert (disk["temperature"], disk["rpm"]) == (-1, 0)
assert disk["health"] == "healthy" # a real disk with thin counters keeps its verdict
def test_a_raid_logical_disk_has_no_drive_health(self):
"""Windows calls the controller's logical disk Healthy; that is no drive's verdict."""
disk = _server().get_disks()[3]
assert (disk["type"], disk["temperature"], disk["health"]) == ("unknown", -1, "unknown")
def test_a_storage_spaces_virtual_disk_is_no_physical_disk(self):
slots = [d["slot"] for d in _server().get_disks()]
assert slots == ["PhysicalDisk0", "PhysicalDisk1", "PhysicalDisk3", "PhysicalDisk4"]
def test_a_virtual_disk_with_empty_counters(self):
"""Temperature -1 and health "unknown", not zeros and not a "healthy" nobody
measured."""
[disk] = _driver(disks=_load("disks_vm.json")).get_disks()
assert disk["temperature"] == -1
assert disk["health"] == "unknown"
assert disk["type"] == "unknown"
def test_bad_news_is_never_unknown(self):
raw = _load("disks_vm.json")
raw["disks"][0]["health"] = "Unhealthy"
assert _driver(disks=raw).get_disks()[0]["health"] == "failed"
def test_a_disk_without_a_number_is_named_by_its_id(self):
raw = _load("disks_vm.json")
raw["disks"][0]["device_id"] = ""
slot = _driver(disks=raw).get_disks()[0]["slot"]
assert slot == "60022480A1B2C3D4E5F60718293A4B5C"
def test_without_the_storage_module_there_are_none(self):
assert _driver(disks={"supported": False}).get_disks() == []
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="disk reading came back empty"):
_driver(disks="").get_disks()
def test_one_disk_arrives_bare(self):
"""ConvertTo-Json unwraps a one-element array; the parse wraps it again."""
raw = _load("disks_vm.json")
raw["disks"] = raw["disks"][0]
assert len(_driver(disks=raw).get_disks()) == 1
# ---------------------------------------------------------------------------
# get_disk_smart
# ---------------------------------------------------------------------------
class TestDiskSmart:
def test_the_reliability_counters_of_an_nvme_ssd(self):
smart = _server().get_disk_smart()
assert smart["PhysicalDisk0"] == {
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"type": "nvme",
"size": 1000204886016,
"health": "ok",
"wearout": None,
"temperature": 41,
"percentage_used": 3,
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": 5120,
"temperature_max": 68,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0,
}
def test_a_disk_with_errors_and_a_warning(self):
entry = _server().get_disk_smart()["PhysicalDisk1"]
assert entry["health"] == "warning"
assert entry["read_errors_uncorrected"] == 12
assert entry["percentage_used"] is None # a spinning disk does not wear out by writes
def test_thin_counters_are_none_where_empty(self):
entry = _server().get_disk_smart()["PhysicalDisk3"]
assert entry["temperature"] is None
assert entry["power_on_hours"] == 30990
assert entry["read_errors_uncorrected"] is None
def test_disks_that_report_nothing_are_left_out(self):
assert set(_server().get_disk_smart()) == {
"PhysicalDisk0",
"PhysicalDisk1",
"PhysicalDisk3",
}
def test_a_virtual_host_has_no_drive_health(self):
assert _driver(disks=_load("disks_vm.json")).get_disk_smart() == {}
def test_without_the_counter_cmdlet_there_is_none(self):
raw = _load("disks_server.json")
raw["counters"] = False
for disk in raw["disks"]:
disk["counter"] = None
assert _driver(disks=raw).get_disk_smart() == {}
def test_without_the_storage_module_there_is_none(self):
assert _driver(disks={"supported": False}).get_disk_smart() == {}
# ---------------------------------------------------------------------------
# get_disk_pools
# ---------------------------------------------------------------------------
class TestPools:
def test_a_degraded_mirror(self):
assert _server().get_disk_pools() == {
"Pool1": {
"name": "Pool1",
"type": "storage-spaces",
"level": "mirror",
"status": "degraded",
"total": 8001574060032,
"used": 2199023255552,
"available": 5802550804480,
"disks": ["PhysicalDisk1", "PhysicalDisk3"],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
}
@pytest.mark.parametrize(
("health", "resiliency", "status", "level"),
[
("Healthy", "Simple", "online", "stripe"),
("Unhealthy", "Parity", "faulted", "parity"),
("Unknown", "", "unknown", "unknown"),
],
)
def test_status_and_level(self, health, resiliency, status, level):
raw = _load("storage_pools.json")
raw["pools"][0].update(health=health, resiliency=resiliency)
pool = _driver(pools=raw).get_disk_pools()["Pool1"]
assert (pool["status"], pool["level"]) == (status, level)
def test_no_pools(self):
assert _driver(pools={"supported": True, "pools": []}).get_disk_pools() == {}
def test_without_storage_spaces_there_are_none(self):
assert _driver(pools={"supported": False}).get_disk_pools() == {}
# ---------------------------------------------------------------------------
# get_volumes
# ---------------------------------------------------------------------------
class TestVolumes:
def test_the_system_drive(self):
assert _server().get_volumes()["C:"] == {
"name": "C:",
"pool": "",
"type": "filesystem",
"total": 999483936768,
"used": 287138238464,
"available": 712345698304,
"mountpoint": "C:\\",
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": "NTFS",
"health": "healthy",
}
def test_a_labelled_volume_with_a_warning(self):
volume = _server().get_volumes()["D:"]
assert (volume["name"], volume["file_system"]) == ("Data", "ReFS")
assert volume.get("health") == "warning"
def test_a_volume_mounted_in_a_folder(self):
volume = _server().get_volumes()["C:\\Logs"]
assert (volume["name"], volume["mountpoint"]) == ("Logs", "C:\\Logs\\")
def test_volumes_mounted_nowhere_are_left_out(self):
"""The EFI system partition and the recovery partition hold no one's data."""
assert list(_server().get_volumes()) == ["C:", "D:", "C:\\Logs"]
def test_without_the_storage_module_there_are_none(self):
assert _driver(volumes={"supported": False}).get_volumes() == {}
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="volume reading came back empty"):
_driver(volumes="").get_volumes()
+2 -4
View File
@@ -14,7 +14,7 @@ import argparse
import getpass
import pathlib
from napalm_windows import WindowsDriver, scheduled_tasks, storage, time_sync
from napalm_windows import WindowsDriver, posture, scheduled_tasks, time_sync
from napalm_windows import windows as mod
SCRIPTS = {
@@ -27,9 +27,7 @@ SCRIPTS = {
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"disks": storage._PS_DISKS,
"storage_pools": storage._PS_STORAGE_POOLS,
"volumes": storage._PS_VOLUMES,
"posture": posture._PS_POSTURE,
}
OUT = pathlib.Path(__file__).parent / "harvest-out"