Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
975eecf0cc |
No files matched your search
+14
-28
@@ -7,34 +7,20 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- The host's SMBIOS identity, what ties it to its BMC (NetOrk/netork#2888):
|
||||
`get_system_identity` reads the system UUID and product serial
|
||||
(`Win32_ComputerSystemProduct`), the board serial (`Win32_BaseBoard`) and the system
|
||||
firmware's vendor, version and release date (`Win32_BIOS`) in one script of its own.
|
||||
Vendor placeholders such as "To be filled by O.E.M." or an all-F UUID read as empty,
|
||||
by napalm-device-types' rules (`clean_system_identity`).
|
||||
- Running processes (NetOrk/netork#2889): `get_processes` lists them the way `ps` does --
|
||||
parent, owner, CPU and memory share, virtual and resident size, start and command line
|
||||
-- from `Win32_Process` and `Get-Process -IncludeUserName` in one script. A process
|
||||
that exited between the two reads, or whose PID was reused in between, is left out.
|
||||
- Local accounts (NetOrk/netork#2889): `get_os_users` lists the host's own accounts with
|
||||
their local groups and profile folder. `uid` is the account's relative identifier
|
||||
(500 for the built-in Administrator), `sid` its whole security identifier. A domain
|
||||
controller, which has no local accounts, and a host without the LocalAccounts cmdlets
|
||||
raise `NotImplementedError`.
|
||||
- Installed software (NetOrk/netork#2890): `get_packages` lists the programs installed
|
||||
for the whole machine from the Uninstall keys, the 64-bit and the 32-bit ones, each
|
||||
with its publisher and architecture; `source` is `msi` or `exe`. Hidden system
|
||||
components and updates listed under their product are left out. Programs installed
|
||||
for one user only, and Store apps, are not read yet; nothing is installed or removed.
|
||||
- Restart required and automatic updates (NetOrk/netork#2891): `get_host_status` says
|
||||
the host needs a restart when Windows Update or component servicing waits for one;
|
||||
pending file renames, a pending update executable and a new computer name are named
|
||||
in the reason but do not count on their own. Automatic updates follow the Windows
|
||||
Update policy (`NoAutoUpdate`, `AUOptions`); without one a Windows client installs on
|
||||
its own and a server follows its local setting. When they last succeeded is the
|
||||
latest successful installation Windows Update recorded; the system drive's size and
|
||||
free space come with it. Nothing searches for updates during the reading.
|
||||
- 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.
|
||||
- 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
|
||||
|
||||
@@ -42,12 +42,9 @@ 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_system_identity` | `Win32_ComputerSystemProduct` (UUID, serial), `Win32_BaseBoard`, `Win32_BIOS`; placeholders empty (napalm-device-types' `clean_system_identity`). See *Host basics* |
|
||||
| `get_processes` | `Win32_Process` joined with `Get-Process -IncludeUserName` by PID and start, shaped like `ps` |
|
||||
| `get_os_users` | `Get-LocalUser`, `Get-LocalGroup` + `Get-LocalGroupMember` (ADSI fallback), `Win32_UserProfile`; the RID as `uid`, the SID as `sid` |
|
||||
| `get_packages` | The machine-wide Uninstall keys, native and `WOW6432Node`; no per-user installs, no Store apps, nothing installed |
|
||||
| `get_host_status` | `Microsoft.Update.SystemInfo`, the registry's restart markers, the Windows Update policy and history, the system drive |
|
||||
| `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 |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
|
||||
@@ -102,31 +99,27 @@ 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 basics
|
||||
### Host firewall
|
||||
|
||||
* **Identity.** Windows decodes the SMBIOS system UUID the way dmidecode does; the
|
||||
release date is CIM's midnight UTC, read as that day.
|
||||
* **Processes.** `cpu` is the CPU time over the time since the start, per logical
|
||||
processor; `memory` the working set over the visible memory; `started` the local time
|
||||
as `ps -o lstart` prints it. Windows has no controlling terminal and no `ps` state:
|
||||
`tty` and `state` are empty. The owner needs an elevated session; without one it is
|
||||
empty. PID 0 (System Idle Process) is no process.
|
||||
* **Local accounts.** `gid` is 513, the primary group of every local account; `home` is
|
||||
the profile folder, empty until the account first logs on; `shell` is empty.
|
||||
* **Packages.** A 32-bit and a 64-bit install of one program are two packages, told
|
||||
apart by `architecture`. Keys without a `DisplayName`, `SystemComponent=1` and
|
||||
entries with a `ParentKeyName` are left out.
|
||||
* **Restart required** is Windows Update's `RebootRequired` (or its registry marker) or
|
||||
component servicing's `RebootPending`. `PendingFileRenameOperations`,
|
||||
`UpdateExeVolatile` and a pending computer rename only make up the reason.
|
||||
* **Automatic updates.** Policy first: `NoAutoUpdate=1` off, `AUOptions` 4 on, 2, 3
|
||||
and 7 off, 5 the local setting. Without a policy a client is on and a server follows
|
||||
its local `AUOptions`; a server with neither reads as unknown. The last success is the
|
||||
latest successful installation Windows Update recorded (its history, the AutoUpdate
|
||||
result, the older registry result); the interval is 31 days, the cadence of the
|
||||
monthly cumulative update.
|
||||
What the exposure chain holds a listening socket against (netork#2894). Read only: no
|
||||
rule is ever written.
|
||||
|
||||
Not yet: Windows Update, health metrics, Hyper-V.
|
||||
* **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.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
"""One reading script's JSON object, which the host readings of this driver share."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def json_object(out: str, what: str) -> dict[str, Any]:
|
||||
"""*out*, a script's ``ConvertTo-Json`` of one object, parsed.
|
||||
|
||||
:raises ValueError: when it is empty or no object, naming *what* was read.
|
||||
"""
|
||||
out = out.strip()
|
||||
raw = json.loads(out) if out else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"the {what} reading came back empty")
|
||||
return raw
|
||||
@@ -1,28 +0,0 @@
|
||||
"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891).
|
||||
|
||||
One mixin made of one module per reading, so the driver names a single base:
|
||||
|
||||
* :mod:`napalm_windows.system_identity` -- ``get_system_identity``
|
||||
* :mod:`napalm_windows.processes` -- ``get_processes``
|
||||
* :mod:`napalm_windows.os_users` -- ``get_os_users``
|
||||
* :mod:`napalm_windows.packages` -- ``get_packages``
|
||||
* :mod:`napalm_windows.host_status` -- ``get_host_status``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_windows.host_status import WindowsHostStatusMixin
|
||||
from napalm_windows.os_users import WindowsOsUsersMixin
|
||||
from napalm_windows.packages import WindowsPackagesMixin
|
||||
from napalm_windows.processes import WindowsProcessesMixin
|
||||
from napalm_windows.system_identity import WindowsSystemIdentityMixin
|
||||
|
||||
|
||||
class WindowsHostBasicsMixin(
|
||||
WindowsSystemIdentityMixin,
|
||||
WindowsProcessesMixin,
|
||||
WindowsOsUsersMixin,
|
||||
WindowsPackagesMixin,
|
||||
WindowsHostStatusMixin,
|
||||
):
|
||||
"""The readings napalm-linux has as a matter of course; each module documents its own."""
|
||||
@@ -0,0 +1,357 @@
|
||||
"""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)
|
||||
@@ -1,230 +0,0 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
:class:`WindowsHostStatusMixin` gives the driver napalm-device-types' ``get_host_status``
|
||||
(``HostStatusDict``) in one script. Each part is read on its own -- a COM object that
|
||||
does not answer over WinRM leaves the rest standing -- and nothing searches for updates:
|
||||
that is the update reading's, and too slow for a poll.
|
||||
|
||||
**Restart required** is what Windows says about its own updates:
|
||||
|
||||
* Windows Update's ``Microsoft.Update.SystemInfo.RebootRequired``, and its registry
|
||||
marker ``WindowsUpdate\\Auto Update\\RebootRequired`` where the COM object did not
|
||||
answer;
|
||||
* component-based servicing's ``RebootPending`` (features, roles, servicing stack).
|
||||
|
||||
Other markers only explain: ``PendingFileRenameOperations``, which antivirus and
|
||||
installers set routinely and which would keep the flag up for days, ``UpdateExeVolatile``
|
||||
and a new computer name taking effect at the next restart. They make up
|
||||
``reboot_reason`` with the two above, and a host with only them needs no restart.
|
||||
|
||||
**Automatic updates** follow the policy (``HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\
|
||||
WindowsUpdate\\AU``): ``NoAutoUpdate=1`` is off; ``AUOptions`` 4 installs on its own,
|
||||
2, 3 and 7 only notify or download; 5 leaves it to the local setting. Without a policy
|
||||
Windows 10 and 11 install on their own, and ignore the local ``AUOptions`` an upgrade may
|
||||
have left; a Windows Server follows its local setting (``sconfig``), and without one the
|
||||
answer is None: what each Server release does then is not established.
|
||||
|
||||
**When they last succeeded** is the latest successful installation Windows Update knows
|
||||
of, whoever started it: its history's last 50 entries, the ``Microsoft.Update.AutoUpdate``
|
||||
result and the older registry result (``Auto Update\\Results\\Install``), whichever is
|
||||
latest. Windows has something to install every month -- the cumulative update -- so
|
||||
automatic updates are meant to have installed something within 31 days
|
||||
(``auto_updates_interval``); on Linux that is the timer's day.
|
||||
|
||||
**Filesystems** are the system drive's size and free space, where updates unpack.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import FilesystemUsageDict, HostStatusDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_AU_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
|
||||
_AU_LOCAL = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
|
||||
_CBS = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"
|
||||
_SESSION_MANAGER = r"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager"
|
||||
_COMPUTER_NAME = r"HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName"
|
||||
|
||||
# WUA's dates are UTC with no kind; IUpdateHistoryEntry.Operation 1 is an installation,
|
||||
# ResultCode 2 succeeded and 3 succeeded with errors.
|
||||
_PS_HOST_STATUS = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function V($path, $name) {{
|
||||
$item = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue
|
||||
if ($item) {{ $item.$name }}
|
||||
}}
|
||||
function Utc($t) {{
|
||||
if ($t) {{ ([DateTimeOffset][DateTime]::SpecifyKind($t, 'Utc')).ToUnixTimeSeconds() }}
|
||||
}}
|
||||
$wu = $null
|
||||
try {{ $wu = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired }} catch {{ }}
|
||||
$installs = $null
|
||||
try {{
|
||||
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
|
||||
$count = $searcher.GetTotalHistoryCount()
|
||||
$installs = @(if ($count -gt 0) {{
|
||||
$searcher.QueryHistory(0, [Math]::Min($count, 50)) | Where-Object {{
|
||||
$_.Operation -eq 1 -and ($_.ResultCode -eq 2 -or $_.ResultCode -eq 3)
|
||||
}} | ForEach-Object {{ Utc $_.Date }}
|
||||
}})
|
||||
}} catch {{ }}
|
||||
$au = $null
|
||||
try {{
|
||||
$results = (New-Object -ComObject Microsoft.Update.AutoUpdate).Results
|
||||
$au = Utc $results.LastInstallationSuccessDate
|
||||
}} catch {{ }}
|
||||
$drive = $null
|
||||
try {{
|
||||
$disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'"
|
||||
if ($disk) {{
|
||||
$drive = [pscustomobject]@{{
|
||||
drive = [string]$disk.DeviceID; size = [int64]$disk.Size; free = [int64]$disk.FreeSpace
|
||||
}}
|
||||
}}
|
||||
}} catch {{ }}
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{{
|
||||
wu_reboot_required = $wu
|
||||
cbs_reboot_pending = Test-Path -LiteralPath '{_CBS}\RebootPending'
|
||||
wu_reboot_key = Test-Path -LiteralPath '{_AU_LOCAL}\RebootRequired'
|
||||
file_renames = [bool](V '{_SESSION_MANAGER}' 'PendingFileRenameOperations')
|
||||
update_exe = [string](V 'HKLM:\SOFTWARE\Microsoft\Updates' 'UpdateExeVolatile')
|
||||
computer_name = [string](V '{_COMPUTER_NAME}\ComputerName' 'ComputerName')
|
||||
active_name = [string](V '{_COMPUTER_NAME}\ActiveComputerName' 'ComputerName')
|
||||
no_auto_update = [string](V '{_AU_POLICY}' 'NoAutoUpdate')
|
||||
au_options = [string](V '{_AU_POLICY}' 'AUOptions')
|
||||
local_au_options = [string](V '{_AU_LOCAL}' 'AUOptions')
|
||||
product_type = [int](Get-CimInstance -ClassName Win32_OperatingSystem).ProductType
|
||||
installs = $installs
|
||||
au_last_install = $au
|
||||
legacy_last_install = [string](V '{_AU_LOCAL}\Results\Install' 'LastSuccessTime')
|
||||
system_drive = $drive
|
||||
}})
|
||||
"""
|
||||
|
||||
#: ``AUOptions``: 2 notify, 3 download and notify, 4 install on a schedule, 7 (Server)
|
||||
#: download, notify to install and to restart; 1 is the older "never check".
|
||||
_AU_OPTIONS = {"1": False, "2": False, "3": False, "4": True, "7": False}
|
||||
#: ``Win32_OperatingSystem.ProductType`` of a client; 2 and 3 are servers.
|
||||
_WORKSTATION = 1
|
||||
#: How often a Windows host has something to install: the monthly cumulative update.
|
||||
MONTHLY = 31 * 86400
|
||||
|
||||
|
||||
def _marker(raw: dict[str, Any], key: str) -> bool:
|
||||
return raw.get(key) is True
|
||||
|
||||
|
||||
#: The markers that explain a restart, in the order they are named, each with its words.
|
||||
_REASONS = (
|
||||
(
|
||||
("wu_reboot_required", "wu_reboot_key"),
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
),
|
||||
(("cbs_reboot_pending",), "component-based servicing has a restart pending"),
|
||||
(
|
||||
("file_renames",),
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _rename(raw: dict[str, Any]) -> str | None:
|
||||
"""The new computer name a restart takes effect with, if there is one."""
|
||||
new, active = str(raw.get("computer_name") or ""), str(raw.get("active_name") or "")
|
||||
if new and active and new.lower() != active.lower():
|
||||
return f"the computer takes its new name {new} at the next restart"
|
||||
return None
|
||||
|
||||
|
||||
def _restart_reasons(raw: dict[str, Any]) -> list[str]:
|
||||
reasons = [text for keys, text in _REASONS if any(_marker(raw, key) for key in keys)]
|
||||
if str(raw.get("update_exe") or "0") != "0":
|
||||
reasons.append("an update waits for a restart (UpdateExeVolatile)")
|
||||
rename = _rename(raw)
|
||||
return [*reasons, rename] if rename else reasons
|
||||
|
||||
|
||||
def _restart_required(raw: dict[str, Any]) -> bool:
|
||||
"""Windows Update or component servicing waits for a restart; see the module."""
|
||||
return any(
|
||||
_marker(raw, key) for key in ("wu_reboot_required", "wu_reboot_key", "cbs_reboot_pending")
|
||||
)
|
||||
|
||||
|
||||
def _auto_updates(raw: dict[str, Any]) -> bool | None:
|
||||
"""Whether the host installs updates on its own; see the module."""
|
||||
if str(raw.get("no_auto_update") or "") == "1":
|
||||
return False
|
||||
policy = _AU_OPTIONS.get(str(raw.get("au_options") or ""))
|
||||
if policy is not None:
|
||||
return policy
|
||||
if int(raw.get("product_type") or 0) == _WORKSTATION:
|
||||
return True
|
||||
return _AU_OPTIONS.get(str(raw.get("local_au_options") or ""))
|
||||
|
||||
|
||||
def _registry_time(value: Any) -> int | None:
|
||||
"""``Results\\Install``'s ``LastSuccessTime``, ``YYYY-MM-DD HH:MM:SS`` in UTC."""
|
||||
try:
|
||||
return calendar.timegm(time.strptime(str(value or ""), "%Y-%m-%d %H:%M:%S"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _last_success(raw: dict[str, Any]) -> int | None:
|
||||
"""The latest successful installation any of the three sources knows of."""
|
||||
known = [*_as_list(raw.get("installs")), raw.get("au_last_install")]
|
||||
known.append(_registry_time(raw.get("legacy_last_install")))
|
||||
times = [int(t) for t in known if isinstance(t, int | float) and t > 0]
|
||||
return max(times, default=None)
|
||||
|
||||
|
||||
def _filesystems(raw: dict[str, Any]) -> list[FilesystemUsageDict] | None:
|
||||
drive = raw.get("system_drive")
|
||||
if not isinstance(drive, dict):
|
||||
return None
|
||||
total, free = int(drive.get("size") or 0), int(drive.get("free") or 0)
|
||||
return [
|
||||
{
|
||||
"mountpoint": f"{drive.get('drive') or ''}\\",
|
||||
"total": total,
|
||||
"used": total - free,
|
||||
"available": free,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def parse_host_status(raw: dict[str, Any]) -> HostStatusDict:
|
||||
"""``_PS_HOST_STATUS``'s JSON as the host status; see the module."""
|
||||
reasons = _restart_reasons(raw)
|
||||
auto = _auto_updates(raw)
|
||||
return {
|
||||
"reboot_required": _restart_required(raw),
|
||||
"reboot_reason": "; ".join(reasons) or None,
|
||||
"auto_updates": auto,
|
||||
"auto_updates_last_success": _last_success(raw),
|
||||
"auto_updates_interval": MONTHLY if auto else None,
|
||||
"filesystems": _filesystems(raw),
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostStatusMixin:
|
||||
"""``get_host_status`` from Windows Update and the registry; 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_status(self) -> HostStatusDict:
|
||||
"""Whether the host needs a restart and installs updates on its own; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_host_status(json_object(self._run_raw(_PS_HOST_STATUS), "host status"))
|
||||
@@ -1,143 +0,0 @@
|
||||
"""Local accounts on Windows as napalm-device-types' ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsOsUsersMixin` gives the driver ``get_os_users``. One script reads the
|
||||
accounts (``Get-LocalUser``), the local groups with their members
|
||||
(``Get-LocalGroupMember``) and the profiles' paths (``Win32_UserProfile``).
|
||||
|
||||
Windows names an account by its security identifier, not a number:
|
||||
|
||||
* ``uid`` is the relative identifier, the SID's last part: 500 for the built-in
|
||||
Administrator, 501 Guest, 1000 and up for accounts created. ``sid`` is the whole SID.
|
||||
* ``gid`` is 513, the primary group every local account has ("None"); Windows offers
|
||||
no other for them.
|
||||
* ``home`` is the profile's folder, empty for an account that never logged on and so
|
||||
has none; ``shell`` is empty.
|
||||
* ``groups`` are the local groups the account is a direct member of. A group whose
|
||||
members cannot be read -- ``Get-LocalGroupMember`` fails on a member SID it cannot
|
||||
resolve, and the ADSI fallback failed too -- names nobody.
|
||||
|
||||
These are the host's own accounts. Who may log in and how (administrators, RDP rights,
|
||||
domain accounts) is the login accounts' contract, not this one. A domain controller
|
||||
has no local accounts -- ``Get-LocalUser`` would list the domain's -- and a host without
|
||||
the LocalAccounts module cannot list them; both raise ``NotImplementedError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import UserDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PS_OS_USERS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
|
||||
$local = [bool](Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue)
|
||||
$users = @()
|
||||
$groups = @()
|
||||
if ($role -lt 4 -and $local) {
|
||||
$homes = @{}
|
||||
Get-CimInstance -ClassName Win32_UserProfile | ForEach-Object {
|
||||
$homes[[string]$_.SID] = [string]$_.LocalPath
|
||||
}
|
||||
$users = @(Get-LocalUser | ForEach-Object {
|
||||
$sid = [string]$_.SID
|
||||
[pscustomobject]@{ name = [string]$_.Name; sid = $sid; home = $homes[$sid] }
|
||||
})
|
||||
$groups = @(Get-LocalGroup | ForEach-Object {
|
||||
$group = $_
|
||||
$members = $null
|
||||
try {
|
||||
$members = @(Get-LocalGroupMember -SID $group.SID | ForEach-Object { [string]$_.SID })
|
||||
} catch {
|
||||
try {
|
||||
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME/$($group.Name),group"
|
||||
$members = @($adsi.psbase.Invoke('Members') | ForEach-Object {
|
||||
$bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)
|
||||
(New-Object System.Security.Principal.SecurityIdentifier($bytes, 0)).Value
|
||||
})
|
||||
} catch { $members = $null }
|
||||
}
|
||||
[pscustomobject]@{ name = [string]$group.Name; members = $members }
|
||||
})
|
||||
}
|
||||
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
domain_role = $role
|
||||
local_accounts = $local
|
||||
users = $users
|
||||
groups = $groups
|
||||
})
|
||||
"""
|
||||
|
||||
#: ``Win32_ComputerSystem.DomainRole`` of a backup and of a primary domain controller.
|
||||
_DOMAIN_CONTROLLER = 4
|
||||
#: DOMAIN_GROUP_RID_USERS: the primary group of every local account.
|
||||
_PRIMARY_GROUP = 513
|
||||
|
||||
|
||||
def _rid(sid: str) -> int:
|
||||
tail = sid.rsplit("-", 1)[-1]
|
||||
return int(tail) if tail.isdigit() else 0
|
||||
|
||||
|
||||
def _memberships(groups: list[Any]) -> dict[str, list[str]]:
|
||||
"""SID -> the names of the groups it is a direct member of, in the order read."""
|
||||
member_of: dict[str, list[str]] = {}
|
||||
for group in groups:
|
||||
members = group.get("members")
|
||||
if members is None:
|
||||
logger.warning("the members of local group %r could not be read", group.get("name"))
|
||||
continue
|
||||
for sid in _as_list(members):
|
||||
member_of.setdefault(str(sid), []).append(str(group["name"]))
|
||||
return member_of
|
||||
|
||||
|
||||
def parse_os_users(raw: dict[str, Any]) -> list[UserDict]:
|
||||
"""``_PS_OS_USERS``'s JSON as ``UserDict``s; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
"""
|
||||
if int(raw.get("domain_role") or 0) >= _DOMAIN_CONTROLLER:
|
||||
raise NotImplementedError(
|
||||
"a domain controller has no local accounts; its accounts are the domain's"
|
||||
)
|
||||
if not raw.get("local_accounts"):
|
||||
raise NotImplementedError("Get-LocalUser is not available on this host")
|
||||
member_of = _memberships(_as_list(raw.get("groups")))
|
||||
users: list[UserDict] = []
|
||||
for user in _as_list(raw.get("users")):
|
||||
sid = str(user.get("sid") or "")
|
||||
users.append(
|
||||
{
|
||||
"username": str(user["name"]),
|
||||
"uid": _rid(sid),
|
||||
"gid": _PRIMARY_GROUP,
|
||||
"home": str(user.get("home") or ""),
|
||||
"shell": "",
|
||||
"groups": member_of.get(sid, []),
|
||||
"sid": sid,
|
||||
}
|
||||
)
|
||||
return users
|
||||
|
||||
|
||||
class WindowsOsUsersMixin:
|
||||
"""``get_os_users`` from the LocalAccounts cmdlets; 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_os_users(self) -> list[UserDict]:
|
||||
"""The host's local accounts; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_os_users(json_object(self._run_raw(_PS_OS_USERS), "local account"))
|
||||
@@ -1,119 +0,0 @@
|
||||
"""Installed software on Windows as packages (NetOrk/netork#2890).
|
||||
|
||||
:class:`WindowsPackagesMixin` gives the driver napalm-device-types' ``get_packages``
|
||||
(``PackageDict``) from the machine-wide Uninstall keys, the list "Apps & features" and
|
||||
``winget list`` read too:
|
||||
|
||||
* ``HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall``: the host's native
|
||||
programs (``x64``, ``arm64`` on ARM, ``x86`` on a 32-bit Windows);
|
||||
* ``HKLM\\SOFTWARE\\WOW6432Node\\...\\Uninstall``: the 32-bit programs of a 64-bit
|
||||
Windows (``x86``).
|
||||
|
||||
A 32-bit and a 64-bit install of one program stay two packages, told apart by
|
||||
``architecture``. Left out: keys without a ``DisplayName``, ``SystemComponent=1``
|
||||
(parts Windows or a suite hides from the list) and entries with a ``ParentKeyName``
|
||||
(updates listed under their product; Windows' own updates are the update history's).
|
||||
``source`` is ``msi`` for a Windows Installer package (``WindowsInstaller=1``), else
|
||||
``exe``; ``size`` is ``EstimatedSize`` (KiB) in bytes, 0 where none is given;
|
||||
``publisher`` is the vendor the program names.
|
||||
|
||||
Not read: per-user installs (a user's own ``HKU`` hive -- over WinRM ``HKCU`` is the
|
||||
connecting account's, and the hives of whoever is logged on would make the list change
|
||||
with them), Store and MSIX apps, and winget, which is a per-user App Execution Alias
|
||||
that does not work reliably in a WinRM session. Nothing is installed or removed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_UNINSTALL = r"Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
|
||||
_PS_PACKAGES = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$native = switch ($env:PROCESSOR_ARCHITECTURE) {{
|
||||
'ARM64' {{ 'arm64' }}
|
||||
'x86' {{ 'x86' }}
|
||||
default {{ 'x64' }}
|
||||
}}
|
||||
$keys = @(
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\{_UNINSTALL}'; arch = $native }},
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\WOW6432Node\{_UNINSTALL}'; arch = 'x86' }}
|
||||
)
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
foreach ($key in $keys) {{
|
||||
if (Test-Path -LiteralPath $key.path) {{
|
||||
Get-ChildItem -LiteralPath $key.path -ErrorAction SilentlyContinue | ForEach-Object {{
|
||||
[pscustomobject]@{{
|
||||
key = [string]$_.PSChildName
|
||||
arch = $key.arch
|
||||
name = [string]$_.GetValue('DisplayName')
|
||||
version = [string]$_.GetValue('DisplayVersion')
|
||||
publisher = [string]$_.GetValue('Publisher')
|
||||
system = [string]$_.GetValue('SystemComponent')
|
||||
parent = [string]$_.GetValue('ParentKeyName')
|
||||
msi = [string]$_.GetValue('WindowsInstaller')
|
||||
size = [string]$_.GetValue('EstimatedSize')
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class WindowsPackageDict(PackageDict):
|
||||
"""A program from the Uninstall keys, with whose it is and which build."""
|
||||
|
||||
publisher: str
|
||||
architecture: str # x64, x86 or arm64
|
||||
|
||||
|
||||
def _size(value: Any) -> int:
|
||||
text = str(value or "").strip()
|
||||
return int(text) * 1024 if text.isdigit() else 0
|
||||
|
||||
|
||||
def _listed(entry: dict[str, Any]) -> bool:
|
||||
"""A program the host lists as installed: named, not hidden, not an update."""
|
||||
return bool(
|
||||
str(entry.get("name") or "").strip()
|
||||
and str(entry.get("system") or "") != "1"
|
||||
and not str(entry.get("parent") or "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _package(entry: dict[str, Any]) -> WindowsPackageDict:
|
||||
return {
|
||||
"name": str(entry["name"]).strip(),
|
||||
"version": str(entry.get("version") or "").strip(),
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": _size(entry.get("size")),
|
||||
"source": "msi" if str(entry.get("msi") or "") == "1" else "exe",
|
||||
"publisher": str(entry.get("publisher") or "").strip(),
|
||||
"architecture": str(entry.get("arch") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_packages(raw: Any) -> list[PackageDict]:
|
||||
"""``_PS_PACKAGES``'s JSON as packages, by name; see the module."""
|
||||
packages = [_package(e) for e in _as_list(raw) if isinstance(e, dict) and _listed(e)]
|
||||
packages.sort(key=lambda p: (p["name"].lower(), p["architecture"]))
|
||||
return list(packages)
|
||||
|
||||
|
||||
class WindowsPackagesMixin:
|
||||
"""``get_packages`` from the Uninstall keys; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_packages(self) -> list[PackageDict]:
|
||||
"""The programs installed for the whole machine; see the module."""
|
||||
return parse_packages(self._run_ps(_PS_PACKAGES))
|
||||
@@ -1,159 +0,0 @@
|
||||
"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes``
|
||||
(``ProcessDict``). One script reads two sources and the join happens here:
|
||||
|
||||
* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time
|
||||
(``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and
|
||||
``VirtualSize``. Read first: it is the list.
|
||||
* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a
|
||||
``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM
|
||||
administrator has; without one the script falls back to ``Get-Process`` and the owner
|
||||
is unknown (empty).
|
||||
|
||||
A process is reported only when both saw it with the same start: one that exited between
|
||||
the two reads is dropped rather than half-filled, and a PID reused in between is another
|
||||
process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves
|
||||
it out.
|
||||
|
||||
The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per
|
||||
logical processor, so 0-100; ``memory`` the working set over the visible memory;
|
||||
``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local
|
||||
time. Windows has no controlling terminal and no process state of that kind: ``tty``
|
||||
and ``state`` are empty. A process without a readable command line (``System``,
|
||||
protected processes) shows its image name. Command lines are reported as the host
|
||||
gives them, as ``ps`` does on Linux.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import ProcessDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_PROCESSES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } }
|
||||
function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } }
|
||||
$os = Get-CimInstance -ClassName Win32_OperatingSystem
|
||||
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
|
||||
$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
pid = [int]$_.ProcessId
|
||||
ppid = [int]$_.ParentProcessId
|
||||
name = [string]$_.Name
|
||||
command = [string]$_.CommandLine
|
||||
started = Unix $_.CreationDate
|
||||
offset = Offset $_.CreationDate
|
||||
cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime
|
||||
ws = [int64]$_.WorkingSetSize
|
||||
vsz = [int64]$_.VirtualSize
|
||||
}
|
||||
})
|
||||
try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) }
|
||||
$owners = @($running | ForEach-Object {
|
||||
$start = $null
|
||||
try { $start = Unix $_.StartTime } catch { }
|
||||
[pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start }
|
||||
})
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{
|
||||
now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
cores = [int]$cs.NumberOfLogicalProcessors
|
||||
memory_kib = [int64]$os.TotalVisibleMemorySize
|
||||
processes = $processes
|
||||
owners = $owners
|
||||
})
|
||||
"""
|
||||
|
||||
#: How far the two sources' starts of one process may differ: they round differently.
|
||||
_SAME_START = 2
|
||||
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
||||
|
||||
|
||||
def _lstart(started: int | None, offset_minutes: int) -> str:
|
||||
"""Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale."""
|
||||
if started is None:
|
||||
return ""
|
||||
t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes)
|
||||
return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}"
|
||||
|
||||
|
||||
class _Host:
|
||||
"""What the reading says about the host as a whole."""
|
||||
|
||||
def __init__(self, raw: dict[str, Any]) -> None:
|
||||
self.now = int(raw.get("now") or 0)
|
||||
self.cores = max(int(raw.get("cores") or 1), 1)
|
||||
self.memory_kib = int(raw.get("memory_kib") or 0)
|
||||
|
||||
def cpu(self, cpu_100ns: int, started: int | None) -> float:
|
||||
if started is None:
|
||||
return 0.0
|
||||
elapsed = max(self.now - started, 1)
|
||||
return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1)
|
||||
|
||||
def memory(self, rss_kib: int) -> float:
|
||||
return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0
|
||||
|
||||
|
||||
def _started(entry: dict[str, Any]) -> int | None:
|
||||
value = entry.get("started")
|
||||
return int(value) if value is not None else None
|
||||
|
||||
|
||||
def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool:
|
||||
"""False when ``Get-Process`` saw another start under this PID: it was reused."""
|
||||
ours, theirs = _started(entry), _started(owner)
|
||||
return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START
|
||||
|
||||
|
||||
def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict:
|
||||
started = _started(entry)
|
||||
rss = int(entry.get("ws") or 0) // 1024
|
||||
return {
|
||||
"pid": int(entry["pid"]),
|
||||
"ppid": int(entry.get("ppid") or 0),
|
||||
"user": str(owner.get("user") or ""),
|
||||
"cpu": host.cpu(int(entry.get("cpu") or 0), started),
|
||||
"memory": host.memory(rss),
|
||||
"vsz": int(entry.get("vsz") or 0) // 1024,
|
||||
"rss": rss,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
"started": _lstart(started, int(entry.get("offset") or 0)),
|
||||
"command": str(entry.get("command") or entry.get("name") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]:
|
||||
"""``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join."""
|
||||
host = _Host(raw)
|
||||
owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))}
|
||||
processes = []
|
||||
for entry in _as_list(raw.get("processes")):
|
||||
owner = owners.get(int(entry["pid"]))
|
||||
if not entry["pid"] or owner is None or not _same_process(entry, owner):
|
||||
continue
|
||||
processes.append(_process(entry, owner, host))
|
||||
return sorted(processes, key=lambda p: p["pid"])
|
||||
|
||||
|
||||
class WindowsProcessesMixin:
|
||||
"""``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries
|
||||
the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_processes(self) -> list[ProcessDict]:
|
||||
"""A snapshot of the running processes, shaped like ``ps``; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))
|
||||
@@ -1,85 +0,0 @@
|
||||
"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888).
|
||||
|
||||
:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the
|
||||
shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which
|
||||
reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes,
|
||||
in one script of its own -- not folded into ``get_facts``, so a class only the identity
|
||||
needs cannot fail the facts:
|
||||
|
||||
* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from
|
||||
SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial);
|
||||
* ``Win32_BaseBoard``: ``SerialNumber``, of the first board;
|
||||
* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives
|
||||
the date as midnight UTC; it travels as Unix time and is read as that UTC day.
|
||||
|
||||
Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import clean_system_identity
|
||||
from napalm_device_types.system_identity import SystemIdentityDict
|
||||
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_SYSTEM_IDENTITY = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct
|
||||
$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1
|
||||
$bios = Get-CimInstance -ClassName Win32_BIOS
|
||||
[pscustomobject]@{
|
||||
uuid = [string]$product.UUID
|
||||
product_serial = [string]$product.IdentifyingNumber
|
||||
board_serial = if ($board) { [string]$board.SerialNumber } else { $null }
|
||||
bios_vendor = [string]$bios.Manufacturer
|
||||
bios_version = [string]$bios.SMBIOSBIOSVersion
|
||||
bios_date = if ($bios.ReleaseDate) {
|
||||
([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds()
|
||||
} else { $null }
|
||||
} | ConvertTo-Json -Compress
|
||||
"""
|
||||
|
||||
|
||||
def _text(raw: dict[str, Any], key: str) -> str:
|
||||
return str(raw.get(key) or "")
|
||||
|
||||
|
||||
def _utc_day(value: Any) -> str:
|
||||
"""Unix time as its UTC day, ``YYYY-MM-DD``; empty for none."""
|
||||
if not isinstance(value, int | float) or isinstance(value, bool):
|
||||
return ""
|
||||
return datetime.fromtimestamp(value, UTC).date().isoformat()
|
||||
|
||||
|
||||
def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict:
|
||||
"""``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty."""
|
||||
return clean_system_identity(
|
||||
system_uuid=_text(raw, "uuid"),
|
||||
product_serial=_text(raw, "product_serial"),
|
||||
board_serial=_text(raw, "board_serial"),
|
||||
bios_vendor=_text(raw, "bios_vendor"),
|
||||
bios_version=_text(raw, "bios_version"),
|
||||
bios_date=_utc_day(raw.get("bios_date")),
|
||||
)
|
||||
|
||||
|
||||
class WindowsSystemIdentityMixin:
|
||||
"""``get_system_identity`` from the CIM classes; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_system_identity(self) -> SystemIdentityDict:
|
||||
"""The host's SMBIOS identity and system firmware, each value empty when unknown
|
||||
or a vendor placeholder; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_system_identity(
|
||||
json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity")
|
||||
)
|
||||
@@ -27,10 +27,11 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.host_basics import WindowsHostBasicsMixin
|
||||
from napalm_windows.host_firewall import WindowsHostFirewallMixin
|
||||
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,7 +264,11 @@ def _is_noise_route(destination: str) -> bool:
|
||||
|
||||
|
||||
class WindowsDriver(
|
||||
WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver
|
||||
WindowsHostFirewallMixin,
|
||||
WindowsFeaturesMixin,
|
||||
WindowsScheduledJobsMixin,
|
||||
WindowsTimeSyncMixin,
|
||||
OSDriver,
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""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)
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"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"}
|
||||
]
|
||||
}
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"wu_reboot_required":false,"cbs_reboot_pending":false,"wu_reboot_key":false,"file_renames":true,"update_exe":"0","computer_name":"WIN01","active_name":"WIN01","no_auto_update":"","au_options":"4","local_au_options":"","product_type":3,"installs":[1763337600,1762732800,1760659200],"au_last_install":1762732800,"legacy_last_install":"","system_drive":{"drive":"C:","size":136363114496,"free":52613349376}}
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"domain_role":2,"local_accounts":true,"users":[{"name":"Administrator","sid":"S-1-5-21-1004336348-1177238915-682003330-500","home":"C:\\Users\\Administrator"},{"name":"DefaultAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-503","home":null},{"name":"Guest","sid":"S-1-5-21-1004336348-1177238915-682003330-501","home":null},{"name":"WDAGUtilityAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-504","home":null},{"name":"svc-backup","sid":"S-1-5-21-1004336348-1177238915-682003330-1001","home":"C:\\Users\\svc-backup"}],"groups":[{"name":"Administrators","members":["S-1-5-21-1004336348-1177238915-682003330-500","S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-21-3623811015-3361044348-30300820-512"]},{"name":"Backup Operators","members":["S-1-5-21-1004336348-1177238915-682003330-1001"]},{"name":"Guests","members":["S-1-5-21-1004336348-1177238915-682003330-501"]},{"name":"Remote Desktop Users","members":[]},{"name":"System Managed Accounts Group","members":["S-1-5-21-1004336348-1177238915-682003330-503"]},{"name":"Users","members":["S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-4","S-1-5-11"]}]}
|
||||
-1
@@ -1 +0,0 @@
|
||||
[{"key":"7-Zip","arch":"x64","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"5846"},{"key":"7-Zip","arch":"x86","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"4870"},{"key":"{90160000-008C-0000-1000-0000000FF1CE}","arch":"x64","name":"Office 16 Click-to-Run Extensibility Component","version":"16.0.17126.20132","publisher":"Microsoft Corporation","system":"1","parent":"","msi":"1","size":"0"},{"key":"{AC76BA86-1033-FFFF-7760-BC15014EA700}","arch":"x86","name":"Adobe Acrobat Reader DC","version":"23.008.20470","publisher":"Adobe","system":"","parent":"","msi":"1","size":"1158000"},{"key":"KB5034441","arch":"x64","name":"Security Update for Windows Server (KB5034441)","version":"","publisher":"Microsoft Corporation","system":"","parent":"Windows Server","msi":"","size":""},{"key":"Git_is1","arch":"x64","name":"Git","version":"2.43.0","publisher":"The Git Development Community","system":"","parent":"","msi":"","size":"309000"},{"key":"AddressBook","arch":"x64","name":"","version":"","publisher":"","system":"","parent":"","msi":"","size":""},{"key":"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}","arch":"x64","name":"Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130","version":"14.38.33130.0","publisher":"Microsoft Corporation","system":"","parent":"","msi":"","size":"20532"}]
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]}
|
||||
@@ -1 +0,0 @@
|
||||
{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600}
|
||||
@@ -0,0 +1,8 @@
|
||||
[
|
||||
{"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}
|
||||
]
|
||||
@@ -0,0 +1,222 @@
|
||||
"""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
|
||||
@@ -1,211 +0,0 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
One script reads Windows Update's own answer (``Microsoft.Update.SystemInfo``), the
|
||||
registry's restart markers, the Windows Update policy and history, and the system
|
||||
drive; a fake transport answers it from tests/fixtures/synthetic/host_status.json: a
|
||||
member server whose policy installs updates automatically, with file renames pending
|
||||
from an installer and nothing else.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types.models import HostStatusDict
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_status as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_status.json"
|
||||
MONTH = 31 * 86400
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _status(**changes: Any) -> HostStatusDict:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
reading = {**json.loads(FIXTURE.read_text()), **changes}
|
||||
d._transport = FakeTransport(json.dumps(reading))
|
||||
return d.get_host_status()
|
||||
|
||||
|
||||
def test_reads_the_host_status():
|
||||
assert _status() == {
|
||||
"reboot_required": False,
|
||||
"reboot_reason": "files wait to be replaced at the next restart "
|
||||
"(PendingFileRenameOperations)",
|
||||
"auto_updates": True,
|
||||
"auto_updates_last_success": 1763337600,
|
||||
"auto_updates_interval": MONTH,
|
||||
"filesystems": [
|
||||
{
|
||||
"mountpoint": "C:\\",
|
||||
"total": 136363114496,
|
||||
"used": 136363114496 - 52613349376,
|
||||
"available": 52613349376,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── restart ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_pending_file_renames_alone_need_no_restart():
|
||||
# Antivirus and installers set them routinely; as a trigger they would keep the flag up.
|
||||
status = _status()
|
||||
assert status["reboot_required"] is False
|
||||
assert "PendingFileRenameOperations" in (status["reboot_reason"] or "")
|
||||
|
||||
|
||||
def test_windows_update_saying_so_needs_a_restart():
|
||||
status = _status(wu_reboot_required=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "Windows Update needs a restart to finish installing updates"
|
||||
|
||||
|
||||
def test_component_servicing_pending_needs_a_restart():
|
||||
status = _status(cbs_reboot_pending=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "component-based servicing has a restart pending"
|
||||
|
||||
|
||||
def test_windows_updates_registry_marker_stands_in_where_its_com_object_did_not_answer():
|
||||
status = _status(wu_reboot_required=None, wu_reboot_key=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
|
||||
|
||||
def test_nothing_pending_needs_no_restart_and_gives_no_reason():
|
||||
status = _status(file_renames=False)
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] is None
|
||||
|
||||
|
||||
def test_every_marker_found_is_named():
|
||||
status = _status(
|
||||
wu_reboot_required=True,
|
||||
cbs_reboot_pending=True,
|
||||
update_exe="1",
|
||||
computer_name="WIN02",
|
||||
)
|
||||
assert status["reboot_reason"] == "; ".join(
|
||||
[
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
"component-based servicing has a restart pending",
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
"an update waits for a restart (UpdateExeVolatile)",
|
||||
"the computer takes its new name WIN02 at the next restart",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_a_rename_alone_needs_no_restart_for_updates():
|
||||
status = _status(file_renames=False, computer_name="WIN02")
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] == "the computer takes its new name WIN02 at the next restart"
|
||||
|
||||
|
||||
# ── automatic updates ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("au_options", "expected"),
|
||||
[("2", False), ("3", False), ("4", True), ("7", False)],
|
||||
ids=["notify", "download-only", "install", "server-notify-install-and-restart"],
|
||||
)
|
||||
def test_the_policys_au_options(au_options, expected):
|
||||
assert _status(au_options=au_options)["auto_updates"] is expected
|
||||
|
||||
|
||||
def test_a_policy_that_turns_automatic_updates_off():
|
||||
assert _status(no_auto_update="1")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_policy_that_leaves_it_to_the_local_administrator():
|
||||
assert _status(au_options="5", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="5", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_client_without_a_policy_installs_updates_itself():
|
||||
assert _status(au_options="", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_client_ignores_a_leftover_local_setting():
|
||||
# Windows 10 and 11 honour only the policy; an old AUOptions left from an upgrade stays.
|
||||
assert _status(au_options="", local_au_options="2", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_server_follows_its_local_setting_without_a_policy():
|
||||
assert _status(au_options="", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_server_without_any_setting_cannot_tell():
|
||||
status = _status(au_options="", local_au_options="")
|
||||
assert status["auto_updates"] is None
|
||||
assert status["auto_updates_interval"] is None
|
||||
|
||||
|
||||
def test_without_automatic_updates_there_is_no_interval():
|
||||
status = _status(au_options="3")
|
||||
assert status["auto_updates_interval"] is None
|
||||
assert status["auto_updates_last_success"] == 1763337600
|
||||
|
||||
|
||||
def test_the_last_success_is_the_latest_any_source_knows():
|
||||
status = _status(installs=[], au_last_install=None, legacy_last_install="2025-11-20 03:12:44")
|
||||
assert status["auto_updates_last_success"] == 1763608364
|
||||
status = _status(installs=[1760659200], au_last_install=1762732800)
|
||||
assert status["auto_updates_last_success"] == 1762732800
|
||||
|
||||
|
||||
def test_no_installation_known_has_no_last_success():
|
||||
status = _status(installs=None, au_last_install=None, legacy_last_install="")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
def test_an_unset_com_date_is_no_installation():
|
||||
# WUA's DATE zero is 1899-12-30, which travels as a negative Unix time.
|
||||
status = _status(installs=[], au_last_install=-2209161600, legacy_last_install="garbage")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
# ── the system drive ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_an_unread_system_drive_is_no_filesystem_reading():
|
||||
assert _status(system_drive=None)["filesystems"] is None
|
||||
|
||||
|
||||
def test_one_script_reads_it_all_each_part_on_its_own():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text())
|
||||
d.get_host_status()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_HOST_STATUS
|
||||
for part in (
|
||||
"Microsoft.Update.SystemInfo",
|
||||
r"Component Based Servicing\RebootPending",
|
||||
"PendingFileRenameOperations",
|
||||
r"Policies\Microsoft\Windows\WindowsUpdate\AU",
|
||||
"QueryHistory",
|
||||
"Win32_LogicalDisk",
|
||||
):
|
||||
assert part in script
|
||||
# Each COM object is asked inside its own try, so one that does not answer over
|
||||
# WinRM leaves the rest of the reading standing.
|
||||
assert script.count("try {") >= 4
|
||||
# No update search in the poll: that is the update reading's, and slow.
|
||||
assert "Search(" not in script
|
||||
@@ -1,103 +0,0 @@
|
||||
"""Local accounts on Windows as ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads ``Get-LocalUser``, ``Get-LocalGroup`` with their members and the
|
||||
profiles' paths; a fake transport answers it from tests/fixtures/synthetic/os_users.json,
|
||||
a member server as Windows installs it plus one account created (``svc-backup``).
|
||||
Windows names an account by its SID: ``uid`` is its relative identifier, ``sid`` the
|
||||
whole of it (napalm-device-types' ``UserDict.sid``).
|
||||
"""
|
||||
|
||||
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 os_users as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "os_users.json"
|
||||
BASE = "S-1-5-21-1004336348-1177238915-682003330"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading(**changes: Any) -> dict[str, Any]:
|
||||
return {**json.loads(FIXTURE.read_text()), **changes}
|
||||
|
||||
|
||||
def _users(reading: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return {u["username"]: u for u in d.get_os_users()}
|
||||
|
||||
|
||||
def test_an_account_created_reads_like_a_posix_one():
|
||||
assert _users()["svc-backup"] == {
|
||||
"username": "svc-backup",
|
||||
"uid": 1001,
|
||||
"gid": 513,
|
||||
"home": "C:\\Users\\svc-backup",
|
||||
"shell": "",
|
||||
"groups": ["Administrators", "Backup Operators", "Users"],
|
||||
"sid": f"{BASE}-1001",
|
||||
}
|
||||
|
||||
|
||||
def test_the_built_in_accounts_keep_their_well_known_rids():
|
||||
users = _users()
|
||||
assert users["Administrator"]["uid"] == 500
|
||||
assert users["Guest"]["uid"] == 501
|
||||
assert users["Guest"]["groups"] == ["Guests"]
|
||||
|
||||
|
||||
def test_an_account_that_never_logged_on_has_no_home():
|
||||
assert _users()["Guest"]["home"] == ""
|
||||
|
||||
|
||||
def test_a_group_whose_members_could_not_be_read_names_nobody():
|
||||
# Get-LocalGroupMember and the ADSI fallback both failed: the script sends null.
|
||||
reading = _reading()
|
||||
reading["groups"][0]["members"] = None
|
||||
assert "Administrators" not in _users(reading)["svc-backup"]["groups"]
|
||||
|
||||
|
||||
def test_a_single_account_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["users"] = reading["users"][0]
|
||||
reading["groups"] = reading["groups"][0]
|
||||
assert _users(reading)["Administrator"]["groups"] == ["Administrators"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [4, 5])
|
||||
def test_a_domain_controller_has_no_local_accounts_to_list(role):
|
||||
with pytest.raises(NotImplementedError, match="domain controller"):
|
||||
_users(_reading(domain_role=role, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_a_host_without_the_local_accounts_cmdlets_cannot_list_them():
|
||||
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
|
||||
_users(_reading(local_accounts=False, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_one_script_reads_accounts_groups_and_profiles():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading()))
|
||||
d.get_os_users()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_OS_USERS
|
||||
for part in ("Get-LocalUser", "Get-LocalGroupMember", "Win32_UserProfile", "DomainRole"):
|
||||
assert part in script
|
||||
# Probed first, so a host without the module says so instead of failing.
|
||||
assert "Get-Command -Name Get-LocalUser" in script
|
||||
@@ -1,123 +0,0 @@
|
||||
"""Installed software on Windows: the machine-wide Uninstall keys (NetOrk/netork#2890).
|
||||
|
||||
One script reads the native and the 32-bit (``WOW6432Node``) Uninstall key of HKLM; a
|
||||
fake transport answers it from tests/fixtures/synthetic/packages.json. The fixture holds
|
||||
the cases the issue names: 7-Zip installed both as a 64-bit and a 32-bit program, a
|
||||
``SystemComponent`` entry, and an update listed under its product (``ParentKeyName``).
|
||||
"""
|
||||
|
||||
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 packages as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "packages.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading() -> list[dict[str, Any]]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: Any = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading() if reading is None else reading))
|
||||
return d
|
||||
|
||||
|
||||
def _packages(reading: Any = None) -> list[Any]:
|
||||
return list(_driver(reading).get_packages())
|
||||
|
||||
|
||||
def test_a_program_reads_as_a_package():
|
||||
git = next(p for p in _packages() if p["name"] == "Git")
|
||||
assert git == {
|
||||
"name": "Git",
|
||||
"version": "2.43.0",
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": 309000 * 1024,
|
||||
"source": "exe",
|
||||
"publisher": "The Git Development Community",
|
||||
"architecture": "x64",
|
||||
}
|
||||
|
||||
|
||||
def test_a_windows_installer_package_is_msi():
|
||||
acrobat = next(p for p in _packages() if p["name"] == "Adobe Acrobat Reader DC")
|
||||
assert acrobat["source"] == "msi"
|
||||
assert acrobat["architecture"] == "x86"
|
||||
|
||||
|
||||
def test_a_32_and_a_64_bit_install_of_one_program_stay_two_packages():
|
||||
zips = [p for p in _packages() if p["name"].startswith("7-Zip")]
|
||||
assert sorted(p["architecture"] for p in zips) == ["x64", "x86"]
|
||||
|
||||
|
||||
def test_system_components_updates_and_unnamed_keys_are_no_packages():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert "Office 16 Click-to-Run Extensibility Component" not in names
|
||||
assert "Security Update for Windows Server (KB5034441)" not in names
|
||||
assert "" not in names
|
||||
assert len(names) == 5
|
||||
|
||||
|
||||
def test_packages_come_sorted_by_name():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert names == sorted(names, key=str.lower)
|
||||
|
||||
|
||||
def test_a_missing_size_is_zero():
|
||||
reading = _reading()
|
||||
reading[5]["size"] = ""
|
||||
assert next(p for p in _packages(reading) if p["name"] == "Git")["size"] == 0
|
||||
|
||||
|
||||
def test_a_single_package_survives_powershells_unwrapping():
|
||||
assert [p["name"] for p in _packages(_reading()[5])] == ["Git"]
|
||||
|
||||
|
||||
def test_a_host_with_nothing_installed_has_no_packages():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("[]")
|
||||
assert d.get_packages() == []
|
||||
|
||||
|
||||
def test_one_script_reads_both_machine_wide_keys_and_no_users_hive():
|
||||
d = _driver()
|
||||
d.get_packages()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PACKAGES
|
||||
assert r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
assert r"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
# The connecting account's own hive says nothing about the host.
|
||||
assert "HKCU" not in script
|
||||
assert "winget" not in script
|
||||
|
||||
|
||||
def test_installing_and_removing_stay_not_offered():
|
||||
assert not hasattr(WindowsDriver, "install_package")
|
||||
assert not hasattr(WindowsDriver, "uninstall_package")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "null"])
|
||||
def test_an_empty_answer_has_no_packages(answer):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(answer)
|
||||
assert d.get_packages() == []
|
||||
@@ -1,125 +0,0 @@
|
||||
"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads both; a fake transport answers it from
|
||||
tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command
|
||||
line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the
|
||||
owner. The fixture holds the cases the join decides:
|
||||
|
||||
* 0, the System Idle Process: no process, left out as ``ps`` leaves it out;
|
||||
* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled;
|
||||
* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID
|
||||
that was reused between the two reads, dropped;
|
||||
* 7777, started after ``Win32_Process`` was read: not part of the reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import processes as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return d
|
||||
|
||||
|
||||
def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]:
|
||||
return {p["pid"]: p for p in _driver(reading).get_processes()}
|
||||
|
||||
|
||||
def test_the_join_keeps_the_processes_both_reads_saw():
|
||||
assert sorted(_by_pid()) == [4, 812, 4312]
|
||||
|
||||
|
||||
def test_a_process_reads_like_ps():
|
||||
assert _by_pid()[4312] == {
|
||||
"pid": 4312,
|
||||
"ppid": 3988,
|
||||
"user": "WIN01\\admin",
|
||||
# 120 CPU seconds in 600 s on 4 logical processors
|
||||
"cpu": 5.0,
|
||||
# 100 MiB of 8 GiB
|
||||
"memory": 1.2,
|
||||
"vsz": 2203500000000 // 1024,
|
||||
"rss": 102400,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
# 11:50 UTC, an hour east of it
|
||||
"started": "Mon Dec 1 12:50:00 2025",
|
||||
"command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo',
|
||||
}
|
||||
|
||||
|
||||
def test_a_process_without_a_command_line_shows_its_name():
|
||||
system = _by_pid()[4]
|
||||
assert system["command"] == "System"
|
||||
assert system["started"] == ""
|
||||
assert system["cpu"] == 0.0
|
||||
|
||||
|
||||
def test_a_start_one_second_apart_is_the_same_process():
|
||||
# Get-Process and CIM round the start differently.
|
||||
reading = _reading()
|
||||
reading["owners"][2]["started"] += 1
|
||||
assert 812 in _by_pid(reading)
|
||||
|
||||
|
||||
def test_without_elevation_the_owner_is_unknown():
|
||||
# Get-Process -IncludeUserName needs an elevated session; the script falls back.
|
||||
reading = _reading()
|
||||
for owner in reading["owners"]:
|
||||
owner.pop("user")
|
||||
assert {p["user"] for p in _by_pid(reading).values()} == {""}
|
||||
|
||||
|
||||
def test_cpu_stays_within_a_hundred_percent():
|
||||
reading = _reading()
|
||||
reading["processes"][3]["cpu"] = 10**13
|
||||
assert _by_pid(reading)[4312]["cpu"] == 100.0
|
||||
|
||||
|
||||
def test_a_single_process_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["processes"] = reading["processes"][2]
|
||||
reading["owners"] = reading["owners"][2]
|
||||
assert sorted(_by_pid(reading)) == [812]
|
||||
|
||||
|
||||
def test_one_script_reads_both_sources():
|
||||
d = _driver()
|
||||
d.get_processes()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PROCESSES
|
||||
assert "Win32_Process" in script
|
||||
assert "Get-Process -IncludeUserName" in script
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_processes()
|
||||
@@ -1,93 +0,0 @@
|
||||
"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888).
|
||||
|
||||
One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``;
|
||||
a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell
|
||||
server as the classes describe it. The placeholders are napalm-device-types' own
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import system_identity as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _driver(**changes: Any) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes}))
|
||||
return d
|
||||
|
||||
|
||||
def test_reads_the_identity_and_the_firmware():
|
||||
assert _driver().get_system_identity() == {
|
||||
"system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732",
|
||||
"product_serial": "4B5QM72",
|
||||
"board_serial": ".4B5QM72.CNCMS0012345AB.",
|
||||
"bios_vendor": "Dell Inc.",
|
||||
"bios_version": "2.19.0",
|
||||
"bios_date": "2023-08-15",
|
||||
}
|
||||
|
||||
|
||||
def test_one_script_reads_the_three_classes():
|
||||
d = _driver()
|
||||
d.get_system_identity()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_SYSTEM_IDENTITY
|
||||
for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"):
|
||||
assert cls in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("product_serial", "To be filled by O.E.M."),
|
||||
("board_serial", "Default string"),
|
||||
("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"),
|
||||
("uuid", "03000200-0400-0500-0006-000700080009"),
|
||||
("bios_vendor", "To be filled by O.E.M."),
|
||||
],
|
||||
)
|
||||
def test_oem_placeholders_read_as_empty(field, value):
|
||||
identity = _driver(**{field: value}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"])
|
||||
def test_a_value_the_host_did_not_give_reads_as_empty(field):
|
||||
# A VM without a base board, a firmware without a release date: null in the JSON.
|
||||
identity = _driver(**{field: None}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
def test_the_release_date_is_the_utc_day():
|
||||
# CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time.
|
||||
assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15"
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_system_identity()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""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
|
||||
+4
-10
@@ -16,13 +16,10 @@ import pathlib
|
||||
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
host_status,
|
||||
os_users,
|
||||
packages,
|
||||
processes,
|
||||
host_firewall,
|
||||
scheduled_tasks,
|
||||
system_identity,
|
||||
time_sync,
|
||||
windows_features,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
@@ -36,11 +33,8 @@ SCRIPTS = {
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
"system_identity": system_identity._PS_SYSTEM_IDENTITY,
|
||||
"processes": processes._PS_PROCESSES,
|
||||
"os_users": os_users._PS_OS_USERS,
|
||||
"packages": packages._PS_PACKAGES,
|
||||
"host_status": host_status._PS_HOST_STATUS,
|
||||
"host_firewall": host_firewall._PS_HOST_FIREWALL,
|
||||
"windows_features": windows_features._PS_WINDOWS_FEATURES,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
Reference in new issue
Block a user