Author SHA1 Message Date
Christian Manivong 0df672fb7c feat(repairs): a caller's limit tightens a run's bound (NetOrk/netork#2899) 2026-12-01 12:53:17 +01:00
Christian Manivong 0bbeebb7a7 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.
2026-12-01 12:49:37 +01:00
20 changed files with 873 additions and 878 deletions

No files matched your search

+10 -14
View File
@@ -7,20 +7,16 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- The host firewall (NetOrk/netork#2894): `get_host_firewall` returns the Windows
Firewall under `windows` (napalm-device-types' `WindowsFirewallDict`), with `sources`
`["windows-firewall"]` and no netfilter chains. It reads the three profiles as the
firewall applies them (on or off, default inbound and outbound action, "block all
incoming connections", whether local rules apply), every enabled rule of the active
policy with its ports, addresses, program, service, interfaces and where it comes from
(group policy included), and the profile each connected interface is in. The filters
are read in bulk, one cmdlet per kind, so a host with hundreds of rules answers in one
script rather than one query per rule. Nothing is written.
- Windows features (NetOrk/netork#2898): `get_windows_features` lists every optional
feature of the host's image with its state (enabled, disabled, absent, unknown) from
`Win32_OptionalFeature`, under the names Windows uses on clients and servers alike
(`SMB1Protocol`, `MSMQ-Server`, `IIS-WebServerRole`, `Microsoft-Hyper-V`). It is what
a CVE that needs a role or feature is held against.
- 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. Each run has its own bound in time,
which a caller's `limit` can tighten. 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
+31 -22
View File
@@ -43,8 +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* |
| `get_host_firewall` | The Windows Firewall under `windows` (no netfilter chains): the profiles' settings in force from `HNetCfg.FwPolicy2`, `AllowLocalFirewallRules` from `Get-NetFirewallProfile`, the enabled rules of `Get-NetFirewallRule -PolicyStore ActiveStore` with every filter read in bulk and joined on `InstanceID`, and `Get-NetConnectionProfile`. See *Host firewall* |
| `get_windows_features` | `Win32_OptionalFeature`: every optional feature of the image with its state, under DISM's names (`SMB1Protocol`, `MSMQ-Server`), a server's roles included |
| `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
@@ -99,29 +98,39 @@ 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.
### Host firewall
What the exposure chain holds a listening socket against (netork#2894). Read only: no
rule is ever written.
* **Profiles:** on or off, the default inbound and outbound action and "block all
incoming connections" as the firewall applies them (`HNetCfg.FwPolicy2`, group
policy over local), and whether group policy lets local rules apply.
* **Rules:** every enabled rule of the active policy (`ActiveStore`, local and group
policy merged), inbound and outbound, each with where it comes from (`local`,
`group_policy`, `dynamic`, ...). Its filters -- ports, addresses, program, service,
app package, interfaces, interface types, IPsec -- are read with one cmdlet per
filter kind (`Get-NetFirewallPortFilter -All`, ...) and joined on the rule's
`InstanceID`: one filter query per rule takes minutes on a few hundred rules.
Addresses become CIDRs (a mask as its prefix, a range as the networks covering it);
Windows' keywords (`LocalSubnet`, `RPC`) are kept in lower case. A block rule whose
filters did not all come back is left out rather than read as blocking everything.
* **Connections:** the profile of each connected interface, from its network's category
(`DomainAuthenticated` is the domain profile); None where that could not be read.
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 | Bound (a caller's `limit` can tighten it) |
|---|---|---|
| `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
-357
View File
@@ -1,357 +0,0 @@
"""The Windows Firewall: profiles, rules and the profile of each connection (NetOrk/netork#2894).
:class:`WindowsHostFirewallMixin` gives the driver ``get_host_firewall``, the getter a
Linux driver answers with netfilter chains. A Windows host answers with napalm-device-types'
``WindowsFirewallDict`` under ``windows``, ``sources`` ``["windows-firewall"]`` and no
chains: its rules belong to profiles, and match a program and a service as well as ports
and addresses, which chains have no place for. Whether a socket is reachable is the
consumer's call; nothing here judges it, and nothing here writes a rule.
**One script, no per-rule queries.** ``Get-NetFirewallRule | Get-NetFirewallPortFilter``
asks the firewall once per rule and takes minutes for a few hundred rules. So every filter
kind is read in bulk (``Get-Net*Filter -All -PolicyStore ActiveStore``), only the enabled
rules' filters leave the host, and the join on the rule's ``InstanceID`` is done here.
- **The active policy** (``ActiveStore``): what the host applies, local rules and group
policy's merged. Each rule says where it comes from (``PolicyStoreSourceType``: local,
group policy, a service's dynamic rule, ...). Only enabled rules are read.
- **The profiles' settings in force** come from the firewall's COM object
(``HNetCfg.FwPolicy2``), which answers with the effective value where
``Get-NetFirewallProfile`` would say ``NotConfigured``: on or off, the default inbound and
outbound action, "block all incoming connections". Whether group policy lets local rules
apply (``AllowLocalFirewallRules``) only ``Get-NetFirewallProfile`` says;
``NotConfigured`` there is the default, which lets them.
- **The profile of each connected interface** is its network's category
(``Get-NetConnectionProfile``): ``DomainAuthenticated`` is the domain profile. Where that
cannot be read, ``connections`` is None -- not "no interface is connected".
**A filter that was not read never widens a block.** Every rule has every filter, so one
missing from the bulk read is a reading that went wrong. An allow rule keeps "any" for it,
which can only make more reachable; a block rule without one is left out, since "any"
would have it block everything.
"""
from __future__ import annotations
import ipaddress
import json
import re
from typing import TYPE_CHECKING, Any
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
from napalm_device_types.host_firewall_models import (
WindowsFirewallConnectionDict,
WindowsFirewallProfileDict,
WindowsFirewallRuleDict,
)
from napalm_device_types.models import HostFirewallDict
from napalm_windows._powershell import _as_list
SOURCE = "windows-firewall"
# The COM object's profile types (NET_FW_PROFILE_TYPE2) and actions (NET_FW_ACTION).
_PS_HOST_FIREWALL = r"""
$ErrorActionPreference = 'Stop'
$store = 'ActiveStore'
$fw = New-Object -ComObject HNetCfg.FwPolicy2
$local = @{}
try {
foreach ($p in @(Get-NetFirewallProfile -PolicyStore $store)) {
$local[([string]$p.Name).ToLower()] = [string]$p.AllowLocalFirewallRules
}
} catch { }
$types = @{ domain = 1; private = 2; public = 4 }
$profiles = @(foreach ($name in @('domain', 'private', 'public')) {
$t = $types[$name]
[pscustomobject]@{
name = $name
enabled = [bool]$fw.FirewallEnabled($t)
default_inbound = [int]$fw.DefaultInboundAction($t)
default_outbound = [int]$fw.DefaultOutboundAction($t)
block_all_inbound = [bool]$fw.BlockAllInboundTraffic($t)
local_rules = $local[$name]
}
})
$rules = @(Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True)
$ids = @{}
foreach ($r in $rules) { $ids[[string]$r.InstanceID] = $true }
function Of($items) { @($items | Where-Object { $ids.ContainsKey([string]$_.InstanceID) }) }
function AsStrings($values) { @($values | ForEach-Object { [string]$_ }) }
$pf = Of (Get-NetFirewallPortFilter -All -PolicyStore ActiveStore)
$af = Of (Get-NetFirewallAddressFilter -All -PolicyStore ActiveStore)
$apf = Of (Get-NetFirewallApplicationFilter -All -PolicyStore ActiveStore)
$sf = Of (Get-NetFirewallServiceFilter -All -PolicyStore ActiveStore)
$if_ = Of (Get-NetFirewallInterfaceFilter -All -PolicyStore ActiveStore)
$itf = Of (Get-NetFirewallInterfaceTypeFilter -All -PolicyStore ActiveStore)
$sec = Of (Get-NetFirewallSecurityFilter -All -PolicyStore ActiveStore)
$connections = $null
try {
$connections = @(Get-NetConnectionProfile | ForEach-Object {
[pscustomobject]@{
interface = [string]$_.InterfaceAlias
category = [string]$_.NetworkCategory
}
})
} catch { $connections = $null }
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
profiles = $profiles
rules = @($rules | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID
name = [string]$_.DisplayName
group = [string]$_.DisplayGroup
direction = [string]$_.Direction
action = [string]$_.Action
profile = [string]$_.Profile
source = [string]$_.PolicyStoreSourceType
}
})
ports = @($pf | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; protocol = [string]$_.Protocol
local = @(AsStrings $_.LocalPort); remote = @(AsStrings $_.RemotePort)
}
})
addresses = @($af | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID
local = @(AsStrings $_.LocalAddress); remote = @(AsStrings $_.RemoteAddress)
}
})
applications = @($apf | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; program = [string]$_.Program; package = [string]$_.Package
}
})
services = @($sf | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; service = [string]$_.Service }
})
interfaces = @($if_ | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; aliases = @(AsStrings $_.InterfaceAlias) }
})
interface_types = @($itf | ForEach-Object {
[pscustomobject]@{ id = [string]$_.InstanceID; types = [string]$_.InterfaceType }
})
security = @($sec | ForEach-Object {
[pscustomobject]@{
id = [string]$_.InstanceID; authentication = [string]$_.Authentication
override_block = [bool]$_.OverrideBlockRules
}
})
connections = $connections
})
"""
#: NET_FW_ACTION: what the COM object answers for a default action.
_ACTIONS = {0: "block", 1: "allow"}
_CATEGORIES = {"domainauthenticated": "domain", "private": "private", "public": "public"}
_PROTOCOLS = {"6": "tcp", "17": "udp", "1": "icmpv4", "58": "icmpv6"}
_ANY = "any"
_CAMEL = re.compile(r"(?<=[a-z])(?=[A-Z])")
#: The filter kinds a rule's matching depends on: a block rule without one is left out.
_REQUIRED = ("ports", "addresses", "applications", "services")
def _snake(value: str) -> str:
"""``GroupPolicy`` -> ``group_policy``, ``RemoteAccess`` -> ``remote_access``."""
return _CAMEL.sub("_", value.strip()).lower()
def _flags(value: Any) -> list[str] | None:
"""An enum of flags as PowerShell prints it (``Domain, Private``); None for ``Any``."""
names = [_snake(v) for v in str(value or "").split(",") if v.strip()]
if not names or _ANY in names:
return None
return names
def _profiles(value: Any) -> list[str] | None:
names = _flags(value)
if names is None:
return None
known: list[str] = [n for n in WINDOWS_FIREWALL_PROFILES if n in names]
return known or None
def _protocol(value: Any) -> str | None:
text = str(value or "").strip().lower()
if not text or text == _ANY:
return None
return _PROTOCOLS.get(text, text)
def _values(value: Any) -> list[str] | None:
"""A filter's list as Windows prints it; None for ``Any`` (or nothing)."""
values = [str(v).strip() for v in _as_list(value) if str(v).strip()]
if not values or any(v.lower() == _ANY for v in values):
return None
return values
def _ports(value: Any) -> list[str] | None:
values = _values(value)
return None if values is None else [v.lower() for v in values]
def _address(text: str) -> list[str]:
"""One address entry as CIDRs: a mask (``10.0.0.0/255.0.0.0``) as its prefix, a range
as the networks that cover it, a single address as a host route; a keyword lowered."""
low, sep, high = text.partition("-")
try:
if sep:
first, last = ipaddress.ip_address(low.strip()), ipaddress.ip_address(high.strip())
return [str(n) for n in ipaddress.summarize_address_range(first, last)]
return [str(ipaddress.ip_network(text, strict=False))]
except (TypeError, ValueError):
return [text.lower()]
def _addresses(value: Any) -> list[str] | None:
values = _values(value)
if values is None:
return None
return [cidr for v in values for cidr in _address(v)]
def _named(value: Any) -> str | None:
"""A program, package or service as named; None for ``Any`` or nothing."""
text = str(value or "").strip()
return None if not text or text.lower() == _ANY else text
def _by_id(raw: dict[str, Any], kind: str) -> dict[str, dict[str, Any]]:
return {str(f.get("id")): f for f in _as_list(raw.get(kind)) if isinstance(f, dict)}
class _Filters:
"""The bulk-read filters of every kind, by rule id."""
def __init__(self, raw: dict[str, Any]) -> None:
self.kinds = {
kind: _by_id(raw, kind)
for kind in (*_REQUIRED, "interfaces", "interface_types", "security")
}
def complete(self, rule_id: str) -> bool:
return all(rule_id in self.kinds[kind] for kind in _REQUIRED)
def of(self, rule_id: str, kind: str) -> dict[str, Any]:
return self.kinds[kind].get(rule_id) or {}
def _rule(rule: dict[str, Any], filters: _Filters) -> WindowsFirewallRuleDict:
rule_id = str(rule.get("id") or "")
ports, addresses = filters.of(rule_id, "ports"), filters.of(rule_id, "addresses")
application, security = filters.of(rule_id, "applications"), filters.of(rule_id, "security")
source = _snake(str(rule.get("source") or ""))
return {
"id": rule_id,
"name": str(rule.get("name") or rule_id),
"group": str(rule.get("group") or "") or None,
"direction": str(rule.get("direction") or "").lower(),
"action": str(rule.get("action") or "").lower(),
"profiles": _profiles(rule.get("profile")),
"protocol": _protocol(ports.get("protocol")),
"local_ports": _ports(ports.get("local")),
"remote_ports": _ports(ports.get("remote")),
"local_addresses": _addresses(addresses.get("local")),
"remote_addresses": _addresses(addresses.get("remote")),
"program": _named(application.get("program")),
"service": _named(filters.of(rule_id, "services").get("service")),
"package": _named(application.get("package")),
"interfaces": _values(filters.of(rule_id, "interfaces").get("aliases")),
"interface_types": _flags(filters.of(rule_id, "interface_types").get("types")),
"authenticated": str(security.get("authentication") or "notrequired").lower()
!= "notrequired",
"override_block": bool(security.get("override_block")),
"source": source or None,
}
def _rules(raw: dict[str, Any]) -> list[WindowsFirewallRuleDict]:
filters = _Filters(raw)
rules: list[WindowsFirewallRuleDict] = []
for rule in _as_list(raw.get("rules")):
if not isinstance(rule, dict):
continue
read = _rule(rule, filters)
if read["action"] == "block" and not filters.complete(read["id"]):
continue
rules.append(read)
return rules
def _setting(value: Any) -> bool | None:
"""``AllowLocalFirewallRules``: ``False`` only where group policy says so."""
text = str(value or "").strip().lower()
if text in ("true", "notconfigured"):
return True
return False if text == "false" else None
def _bool(value: Any) -> bool | None:
return value if isinstance(value, bool) else None
def _profile(raw: dict[str, Any]) -> WindowsFirewallProfileDict:
return {
"name": str(raw.get("name") or ""),
"enabled": _bool(raw.get("enabled")),
"default_inbound": _ACTIONS.get(raw.get("default_inbound")), # type: ignore[arg-type]
"default_outbound": _ACTIONS.get(raw.get("default_outbound")), # type: ignore[arg-type]
"block_all_inbound": _bool(raw.get("block_all_inbound")),
"local_rules": _setting(raw.get("local_rules")),
}
def _connections(value: Any) -> list[WindowsFirewallConnectionDict] | None:
if value is None:
return None
found: list[WindowsFirewallConnectionDict] = []
for entry in _as_list(value):
if not isinstance(entry, dict):
continue
profile = _CATEGORIES.get(str(entry.get("category") or "").lower())
if profile and entry.get("interface"):
found.append({"interface": str(entry["interface"]), "profile": profile})
return found
def parse_host_firewall(raw: Any) -> HostFirewallDict:
"""What ``_PS_HOST_FIREWALL`` emitted, joined and normalised.
:raises ValueError: when the reading came back empty or without the profiles.
"""
if not isinstance(raw, dict):
raise ValueError("the firewall reading came back empty")
profiles = [_profile(p) for p in _as_list(raw.get("profiles")) if isinstance(p, dict)]
if not profiles:
raise ValueError("the firewall reading has no profiles")
return {
"sources": [SOURCE],
"chains": [],
"windows": {
"profiles": profiles,
"rules": _rules(raw),
"connections": _connections(raw.get("connections")),
},
}
class WindowsHostFirewallMixin:
"""``get_host_firewall`` for a Windows host; 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_host_firewall(self) -> HostFirewallDict:
"""The Windows Firewall's profiles, enabled rules and the profile of each
connected interface, under ``windows``; see the module.
:raises ValueError: when the reading came back empty or without the profiles.
"""
out = self._run_raw(_PS_HOST_FIREWALL).strip()
return parse_host_firewall(json.loads(out) if out else None)
+268
View File
@@ -0,0 +1,268 @@
"""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:<tool>``; every script ends with ``napalm-exit-code:<n>``.
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; a caller's ``limit`` can only tighten it.
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, limit: float | 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, limit)
def check_component_store(
self, *, log: LineLog | None = None, limit: float | 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, limit)
def update_antimalware_signatures(
self, *, log: LineLog | None = None, limit: float | None = None
) -> HostRepairResultDict:
"""``Update-MpSignature``, with the signature version before and after."""
return self._tool_run(
_PS_SIGNATURE_UPDATE, "Update-MpSignature", SIGNATURE_LIMIT, log, limit
)
def scan_antimalware(
self, quick: bool = True, *, log: LineLog | None = None, limit: float | 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, limit)
return self._tool_run(_PS_FULL_SCAN, "Start-MpScan", FULL_SCAN_LIMIT, log, limit)
def _tool_run(
self, script: str, tool: str, bound: float, log: LineLog | None, limit: float | None
) -> HostRepairResultDict:
"""Run *script*; within *bound*, or the caller's *limit* where that is tighter."""
limit = bound if limit is None else min(limit, bound)
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)
+50
View File
@@ -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.
+2 -9
View File
@@ -27,11 +27,10 @@ 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_firewall import WindowsHostFirewallMixin
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
from napalm_windows.windows_features import WindowsFeaturesMixin
logger = logging.getLogger(__name__)
@@ -263,13 +262,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(
WindowsHostFirewallMixin,
WindowsFeaturesMixin,
WindowsScheduledJobsMixin,
WindowsTimeSyncMixin,
OSDriver,
):
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsRepairsMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
-71
View File
@@ -1,71 +0,0 @@
"""Windows optional features: which roles and features a host has on (NetOrk/netork#2898).
:class:`WindowsFeaturesMixin` implements napalm-device-types'
:class:`~napalm_device_types.windows_features.WindowsFeaturesMixin`: the facts a CVE that
needs a role or feature -- the DNS Server, Hyper-V, IIS, SMB 1.0, Message Queuing --
is held against.
**One CIM query** (``Win32_OptionalFeature``), not ``Get-WindowsOptionalFeature -Online``,
which loads the DISM module and takes far longer, and not Server Manager's
``Get-WindowsFeature``, which a client has not. The class lists every feature the image
knows, on a client and a server, under the names DISM gives them (``SMB1Protocol``,
``MSMQ-Server``, ``IIS-WebServerRole``); a server's roles are among them under those
names. ``InstallState`` is 1 enabled, 2 disabled, 3 absent (the payload removed),
4 unknown. A pending change shows as the state the feature has now.
No feature at all is a reading that went wrong -- every image has features -- and raises
rather than reading as a host with none.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from napalm_device_types import WindowsFeaturesMixin as _Contract
from napalm_device_types.windows_features import WindowsFeatureDict, WindowsFeaturesDict
from napalm_windows._powershell import _as_list
_PS_WINDOWS_FEATURES = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_OptionalFeature | ForEach-Object {
[pscustomobject]@{ name = [string]$_.Name; state = [int]$_.InstallState }
}
)
"""
#: Win32_OptionalFeature's InstallState.
_STATES = {1: "enabled", 2: "disabled", 3: "absent", 4: "unknown"}
def parse_windows_features(raw: Any) -> WindowsFeaturesDict:
"""What ``_PS_WINDOWS_FEATURES`` emitted, as names and states.
:raises ValueError: when no feature came back.
"""
features: list[WindowsFeatureDict] = []
for entry in _as_list(raw):
name = str(entry.get("name") or "").strip() if isinstance(entry, dict) else ""
if name:
features.append({"name": name, "state": _STATES.get(entry.get("state"), "unknown")})
if not features:
raise ValueError("the Windows features reading came back without features")
return {"features": features}
class WindowsFeaturesMixin(_Contract):
"""``get_windows_features`` for a Windows host; 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_windows_features(self) -> WindowsFeaturesDict:
"""Every optional feature of the host's image with its state; see the module.
:raises ValueError: when no feature came back.
"""
out = self._run_raw(_PS_WINDOWS_FEATURES).strip()
return parse_windows_features(json.loads(out) if out else None)
+4
View File
@@ -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:<n>`. They follow Microsoft's documented output of
`sfc`, `DISM` and the Defender cmdlets; `tools/harvest.py --runs` records the real ones.
+5
View File
@@ -0,0 +1,5 @@
Scan started: QuickScan
Scan ended.
Threats detected: 1
Virus:DOS/EICAR_Test_File: action succeeded
napalm-exit-code:0
@@ -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
+10
View File
@@ -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
+14
View File
@@ -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
-72
View File
@@ -1,72 +0,0 @@
{
"profiles": [
{"name": "domain", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "NotConfigured"},
{"name": "private", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "True"},
{"name": "public", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "False"}
],
"rules": [
{"id": "RemoteDesktop-UserMode-In-TCP", "name": "Remote Desktop - User Mode (TCP-In)", "group": "Remote Desktop", "direction": "Inbound", "action": "Allow", "profile": "Any", "source": "Local"},
{"id": "FPS-SMB-In-TCP", "name": "File and Printer Sharing (SMB-In)", "group": "File and Printer Sharing", "direction": "Inbound", "action": "Allow", "profile": "Domain, Private", "source": "Local"},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "name": "Windows Remote Management (HTTP-In)", "group": "Windows Remote Management", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "name": "Line of business app", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "name": "Block SQL Server from the internet", "group": "", "direction": "Inbound", "action": "Block", "profile": "Public", "source": "GroupPolicy"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "name": "Management subnets", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Domain", "source": "GroupPolicy"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "name": "Block an unread filter", "group": "", "direction": "Inbound", "action": "Block", "profile": "Any", "source": "Local"},
{"id": "CoreNet-DNS-Out-UDP", "name": "Core Networking - DNS (UDP-Out)", "group": "Core Networking", "direction": "Outbound", "action": "Allow", "profile": "Any", "source": "Local"}
],
"ports": [
{"id": "RemoteDesktop-UserMode-In-TCP", "protocol": "TCP", "local": ["3389"], "remote": ["Any"]},
{"id": "FPS-SMB-In-TCP", "protocol": "TCP", "local": ["445"], "remote": ["Any"]},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "protocol": "TCP", "local": ["5985"], "remote": ["Any"]},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "protocol": "Any", "local": ["Any"], "remote": ["Any"]},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "protocol": "6", "local": ["1433", "1434"], "remote": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "protocol": "TCP", "local": ["RPC", "49152-65535"], "remote": ["Any"]},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "protocol": "TCP", "local": ["8080"], "remote": ["Any"]},
{"id": "CoreNet-DNS-Out-UDP", "protocol": "UDP", "local": ["Any"], "remote": ["53"]}
],
"addresses": [
{"id": "RemoteDesktop-UserMode-In-TCP", "local": ["Any"], "remote": ["Any"]},
{"id": "FPS-SMB-In-TCP", "local": ["Any"], "remote": ["LocalSubnet"]},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "local": ["Any"], "remote": ["LocalSubnet"]},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "local": ["Any"], "remote": ["Any"]},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "local": ["Any"], "remote": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "local": ["Any"], "remote": ["10.0.0.0/255.0.0.0", "192.0.2.1-192.0.2.6", "2001:db8::/48", "198.51.100.7"]},
{"id": "CoreNet-DNS-Out-UDP", "local": ["Any"], "remote": ["DNS"]}
],
"applications": [
{"id": "RemoteDesktop-UserMode-In-TCP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""},
{"id": "FPS-SMB-In-TCP", "program": "System", "package": ""},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "program": "System", "package": ""},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "program": "C:\\Program Files\\Contoso\\lob.exe", "package": ""},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "program": "Any", "package": ""},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "program": "Any", "package": "S-1-15-2-1"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "program": "Any", "package": ""},
{"id": "CoreNet-DNS-Out-UDP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""}
],
"services": [
{"id": "RemoteDesktop-UserMode-In-TCP", "service": "TermService"},
{"id": "FPS-SMB-In-TCP", "service": "Any"},
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "service": "Any"},
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "service": "Any"},
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "service": "Any"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "service": "*"},
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "service": "Any"},
{"id": "CoreNet-DNS-Out-UDP", "service": "dnscache"}
],
"interfaces": [
{"id": "RemoteDesktop-UserMode-In-TCP", "aliases": ["Any"]},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "aliases": ["Ethernet0"]}
],
"interface_types": [
{"id": "RemoteDesktop-UserMode-In-TCP", "types": "Any"},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "types": "Wired, RemoteAccess"}
],
"security": [
{"id": "RemoteDesktop-UserMode-In-TCP", "authentication": "NotRequired", "override_block": false},
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "authentication": "Required", "override_block": true}
],
"connections": [
{"interface": "Ethernet0", "category": "DomainAuthenticated"},
{"interface": "Ethernet1", "category": "Public"}
]
}
+10
View File
@@ -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
-8
View File
@@ -1,8 +0,0 @@
[
{"name": "SMB1Protocol", "state": 2},
{"name": "MSMQ-Server", "state": 1},
{"name": "IIS-WebServerRole", "state": 1},
{"name": "Microsoft-Hyper-V", "state": 3},
{"name": "DNS-Server-Full-Role", "state": 4},
{"name": "Printing-PrintToPDFServices-Features", "state": 1}
]
-222
View File
@@ -1,222 +0,0 @@
"""The Windows Firewall as the exposure chain reads it (NetOrk/netork#2894).
The script reads the profiles from the firewall's own COM object (the settings in
force, group policy over local), the enabled rules of the active policy, and every
filter in bulk -- one cmdlet per filter kind, never one per rule -- and the profile
of each connected interface. The rules and their filters are joined here, on the
rule's InstanceID. The fixture is what the script emits on a Windows Server.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
from napalm_windows import WindowsDriver
from napalm_windows import host_firewall as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_firewall.json"
class FakeHost:
def __init__(self, answer: Any) -> 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 if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(answer: Any = None) -> dict[str, Any]:
driver = WindowsDriver("win", "u", "p")
host = FakeHost(json.loads(FIXTURE.read_text()) if answer is None else answer)
driver._transport = host # type: ignore[assignment]
reading = driver.get_host_firewall()
assert host.sent == [mod._PS_HOST_FIREWALL]
return dict(reading)
def _rule(reading: dict[str, Any], name: str) -> dict[str, Any]:
return next(r for r in reading["windows"]["rules"] if r["name"] == name)
def test_a_windows_reading_has_no_chains_and_names_its_source():
reading = _read()
assert reading["sources"] == ["windows-firewall"]
assert reading["chains"] == []
def test_the_profiles_are_the_settings_in_force():
profiles = _read()["windows"]["profiles"]
assert [p["name"] for p in profiles] == list(WINDOWS_FIREWALL_PROFILES)
assert profiles[0] == {
"name": "domain",
"enabled": True,
"default_inbound": "block",
"default_outbound": "allow",
"block_all_inbound": False,
# NotConfigured: the default, which lets local rules apply.
"local_rules": True,
}
assert profiles[2]["local_rules"] is False
def test_a_rule_carries_its_filters_joined_on_its_instance_id():
rdp = _rule(_read(), "Remote Desktop - User Mode (TCP-In)")
assert rdp == {
"id": "RemoteDesktop-UserMode-In-TCP",
"name": "Remote Desktop - User Mode (TCP-In)",
"group": "Remote Desktop",
"direction": "inbound",
"action": "allow",
"profiles": None,
"protocol": "tcp",
"local_ports": ["3389"],
"remote_ports": None,
"local_addresses": None,
"remote_addresses": None,
"program": "%SystemRoot%\\system32\\svchost.exe",
"service": "TermService",
"package": None,
"interfaces": None,
"interface_types": None,
"authenticated": False,
"override_block": False,
"source": "local",
}
def test_profiles_protocol_numbers_and_port_keywords_are_normalised():
reading = _read()
smb = _rule(reading, "File and Printer Sharing (SMB-In)")
assert smb["profiles"] == ["domain", "private"]
assert smb["remote_addresses"] == ["localsubnet"]
assert smb["program"] == "System"
sql = _rule(reading, "Block SQL Server from the internet")
assert (sql["action"], sql["protocol"], sql["local_ports"]) == (
"block",
"tcp",
["1433", "1434"],
)
assert sql["source"] == "group_policy"
mgmt = _rule(reading, "Management subnets")
assert mgmt["local_ports"] == ["rpc", "49152-65535"]
def test_addresses_become_cidrs_masks_and_ranges_included():
mgmt = _rule(_read(), "Management subnets")
assert mgmt["remote_addresses"] == [
"10.0.0.0/8",
"192.0.2.1/32",
"192.0.2.2/31",
"192.0.2.4/31",
"192.0.2.6/32",
"2001:db8::/48",
"198.51.100.7/32",
]
def test_a_range_across_families_is_kept_as_written():
raw = json.loads(FIXTURE.read_text())
raw["addresses"][0]["remote"] = ["10.0.0.1-::1"]
rdp = _rule(_read(raw), "Remote Desktop - User Mode (TCP-In)")
assert rdp["remote_addresses"] == ["10.0.0.1-::1"]
def test_the_rarer_filters_are_kept():
mgmt = _rule(_read(), "Management subnets")
assert mgmt["interfaces"] == ["Ethernet0"]
assert mgmt["interface_types"] == ["wired", "remote_access"]
assert mgmt["package"] == "S-1-15-2-1"
assert mgmt["service"] == "*"
assert (mgmt["authenticated"], mgmt["override_block"]) == (True, True)
def test_a_block_rule_whose_filter_was_not_read_is_left_out():
# A filter left unread would read as "any" and make the rule block everything.
names = [r["name"] for r in _read()["windows"]["rules"]]
assert "Block an unread filter" not in names
assert "Core Networking - DNS (UDP-Out)" in names
def test_an_allow_rule_whose_filter_was_not_read_matches_more_not_less():
raw = json.loads(FIXTURE.read_text())
raw["addresses"] = [a for a in raw["addresses"] if a["id"] != "FPS-SMB-In-TCP"]
smb = _rule(_read(raw), "File and Printer Sharing (SMB-In)")
assert smb["remote_addresses"] is None
def test_each_connection_names_its_profile():
connections = _read()["windows"]["connections"]
assert connections == [
{"interface": "Ethernet0", "profile": "domain"},
{"interface": "Ethernet1", "profile": "public"},
]
def test_connections_that_could_not_be_read_are_none_not_empty():
raw = json.loads(FIXTURE.read_text())
raw["connections"] = None
assert _read(raw)["windows"]["connections"] is None
def test_an_unknown_category_and_setting_say_nothing():
raw = json.loads(FIXTURE.read_text())
raw["connections"] = [{"interface": "Wi-Fi", "category": "Something"}, "junk"]
raw["rules"].append("junk")
raw["profiles"][0].update(default_inbound=7, local_rules=None, enabled=None)
windows = _read(raw)["windows"]
assert windows["connections"] == []
domain = windows["profiles"][0]
assert (domain["default_inbound"], domain["local_rules"], domain["enabled"]) == (
None,
None,
None,
)
def test_one_element_lists_arrive_bare_and_are_still_lists():
raw = json.loads(FIXTURE.read_text())
raw["rules"] = raw["rules"][0]
raw["ports"] = {**raw["ports"][0], "local": "3389"}
raw["addresses"] = raw["addresses"][0]
raw["applications"] = raw["applications"][0]
raw["services"] = raw["services"][0]
(rule,) = _read(raw)["windows"]["rules"]
assert rule["local_ports"] == ["3389"]
def test_a_reading_without_profiles_is_refused():
with pytest.raises(ValueError, match="firewall"):
_read("")
raw = json.loads(FIXTURE.read_text())
raw["profiles"] = []
with pytest.raises(ValueError, match="profiles"):
_read(raw)
def test_the_script_reads_every_filter_in_bulk():
script = mod._PS_HOST_FIREWALL
for cmdlet in (
"Get-NetFirewallPortFilter",
"Get-NetFirewallAddressFilter",
"Get-NetFirewallApplicationFilter",
"Get-NetFirewallServiceFilter",
"Get-NetFirewallInterfaceFilter",
"Get-NetFirewallInterfaceTypeFilter",
"Get-NetFirewallSecurityFilter",
):
assert f"{cmdlet} -All -PolicyStore ActiveStore" in script
assert "Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True" in script
# Never a filter per rule: no pipeline from the rules into a filter cmdlet.
assert "| Get-NetFirewall" not in script
assert "$ErrorActionPreference = 'Stop'" in script
+326
View File
@@ -0,0 +1,326 @@
"""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/<run>.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 TestLimit:
@pytest.mark.parametrize(
("run", "bound"),
[
(lambda d, **kw: d.verify_system_files(**kw), mod.SFC_LIMIT),
(lambda d, **kw: d.check_component_store(**kw), mod.DISM_LIMIT),
(lambda d, **kw: d.update_antimalware_signatures(**kw), mod.SIGNATURE_LIMIT),
(lambda d, **kw: d.scan_antimalware(**kw), mod.QUICK_SCAN_LIMIT),
(lambda d, **kw: d.scan_antimalware(False, **kw), mod.FULL_SCAN_LIMIT),
],
)
def test_a_callers_limit_tightens_the_bound_never_widens_it(self, run, bound):
driver, transport = _driver(["napalm-exit-code:0"])
run(driver, limit=600)
run(driver, limit=bound * 2)
run(driver)
assert transport.limits == [600, bound, bound]
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
+108
View File
@@ -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()
-93
View File
@@ -1,93 +0,0 @@
"""Windows optional features, the facts a role's CVE precondition is held against (NetOrk/netork#2898).
``Win32_OptionalFeature`` lists every feature of the image, on a client and a server,
under the names ``Get-WindowsOptionalFeature`` uses; its ``InstallState`` is 1 enabled,
2 disabled, 3 absent, 4 unknown. The fixture is what the script emits.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import WindowsFeaturesMixin
from napalm_windows import WindowsDriver
from napalm_windows import windows_features as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "windows_features.json"
class FakeHost:
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 close(self) -> None:
self.is_open = False
def _read(answer: Any = None) -> dict[str, Any]:
driver = WindowsDriver("win", "u", "p")
text = FIXTURE.read_text() if answer is None else answer
host = FakeHost(text if isinstance(text, str) else json.dumps(text))
driver._transport = host # type: ignore[assignment]
reading = driver.get_windows_features()
assert host.sent == [mod._PS_WINDOWS_FEATURES]
return dict(reading)
def test_the_driver_declares_the_contract():
assert issubclass(WindowsDriver, WindowsFeaturesMixin)
def test_every_feature_comes_with_its_state():
assert _read()["features"] == [
{"name": "SMB1Protocol", "state": "disabled"},
{"name": "MSMQ-Server", "state": "enabled"},
{"name": "IIS-WebServerRole", "state": "enabled"},
{"name": "Microsoft-Hyper-V", "state": "absent"},
{"name": "DNS-Server-Full-Role", "state": "unknown"},
{"name": "Printing-PrintToPDFServices-Features", "state": "enabled"},
]
def test_a_state_outside_the_four_is_unknown_and_a_nameless_entry_is_dropped():
raw = [
{"name": "X", "state": 9},
{"name": "", "state": 1},
"junk",
{"name": "Y", "state": None},
]
assert _read(raw)["features"] == [
{"name": "X", "state": "unknown"},
{"name": "Y", "state": "unknown"},
]
def test_one_feature_arrives_bare_and_is_still_a_list():
assert _read({"name": "SMB1Protocol", "state": 1})["features"] == [
{"name": "SMB1Protocol", "state": "enabled"}
]
def test_no_feature_at_all_is_a_reading_that_went_wrong():
# Every image has features; none read is not "none switched on".
with pytest.raises(ValueError, match="features"):
_read("")
with pytest.raises(ValueError, match="features"):
_read([])
def test_the_script_asks_cim_not_dism():
script = mod._PS_WINDOWS_FEATURES
assert "Win32_OptionalFeature" in script
assert "$ErrorActionPreference = 'Stop'" in script
assert "-InputObject @(" in script
+32 -10
View File
@@ -1,11 +1,15 @@
"""Record what the driver's PowerShell scripts emit on a real Windows host.
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure] [--runs]
Asks for the password, runs every getter script over one WinRM connection and
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
MAC and IP addresses and host names before copying anything into tests/.
``--runs`` also records the repair runs' output (``RUNS``), one output object per
line in <run>.txt. They take up to an hour together, and two of them act on the
host: the Defender signature update and a quick scan.
"""
from __future__ import annotations
@@ -14,13 +18,7 @@ import argparse
import getpass
import pathlib
from napalm_windows import (
WindowsDriver,
host_firewall,
scheduled_tasks,
time_sync,
windows_features,
)
from napalm_windows import WindowsDriver, repairs, scheduled_tasks, time_sync
from napalm_windows import windows as mod
SCRIPTS = {
@@ -33,8 +31,14 @@ SCRIPTS = {
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"host_firewall": host_firewall._PS_HOST_FIREWALL,
"windows_features": windows_features._PS_WINDOWS_FEATURES,
}
# Recorded only with --runs: streamed, long, and two of them change the host.
RUNS = {
"sfc_verifyonly": (repairs._PS_SFC_VERIFY, repairs.SFC_LIMIT),
"dism_scanhealth": (repairs._PS_DISM_SCAN, repairs.DISM_LIMIT),
"defender_signature_update": (repairs._PS_SIGNATURE_UPDATE, repairs.SIGNATURE_LIMIT),
"defender_quick_scan": (repairs._PS_QUICK_SCAN, repairs.QUICK_SCAN_LIMIT),
}
OUT = pathlib.Path(__file__).parent / "harvest-out"
@@ -47,6 +51,7 @@ def main() -> None:
ap.add_argument("label", help="subdirectory name, e.g. server2022 or win11")
ap.add_argument("--port", type=int, default=5986)
ap.add_argument("--insecure", action="store_true", help="skip certificate validation")
ap.add_argument("--runs", action="store_true", help="also record the repair runs (RUNS)")
args = ap.parse_args()
driver = WindowsDriver(
@@ -69,10 +74,27 @@ def main() -> None:
else:
print(f" {name}: {len(raw)} bytes")
(target / f"{name}.json").write_text(raw + "\n")
for name, (script, limit) in RUNS.items() if args.runs else ():
_record_run(driver, target, name, script, limit)
finally:
driver.close()
print(f"written to {target}")
def _record_run(
driver: WindowsDriver, target: pathlib.Path, name: str, script: str, limit: int
) -> None:
"""One repair run's output objects as the host sent them, NULs and all."""
assert driver._transport is not None
try:
lines = driver._transport.run_streaming(script, lambda _line: None, limit=limit)
except Exception as exc: # record the failure, keep harvesting
lines = []
print(f" {name}: FAILED — {exc}")
else:
print(f" {name}: {len(lines)} lines")
(target / f"{name}.txt").write_text("".join(f"{line}\n" for line in lines))
if __name__ == "__main__":
main()