47 Commits
Author SHA1 Message Date
christianmanivong 61bbf91e32 Merge pull request 'chore(release): 0.3.0' (#13) from chore/release-0.3.0 into main
driver / lowest (push) Successful in 37s
driver / standard (push) Successful in 24s
driver / lint (push) Successful in 19s
driver / types (push) Successful in 1m13s
driver / test (3.13) (push) Successful in 1m16s
driver / test (3.12) (push) Successful in 1m22s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m4s
driver / publish (push) Successful in 31s
CI / driver (push) Successful in 2m56s
2026-12-02 23:14:54 +00:00
Christian Manivong ae93cb392f chore(release): 0.3.0
driver / lint (pull_request) Successful in 16s
driver / standard (pull_request) Successful in 19s
driver / lowest (pull_request) Successful in 30s
driver / types (pull_request) Successful in 1m8s
driver / test (3.12) (pull_request) Successful in 1m13s
driver / test (3.13) (pull_request) Successful in 1m11s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m7s
CI / driver (pull_request) Successful in 1m57s
driver / publish (pull_request) Skipped
2026-12-03 00:12:33 +01:00
christianmanivong bf76e84a6e Merge pull request 'feat: Windows host depth — identity, packages, updates, posture, firewall, logins, storage, events, repairs (NetOrk/netork#2888–#2899)' (#12) from chore/merge-train-windows-depth into main
driver / lint (push) Successful in 14s
driver / standard (push) Successful in 16s
driver / lowest (push) Successful in 34s
driver / test (3.12) (push) Successful in 1m1s
driver / types (push) Successful in 1m3s
driver / test (3.13) (push) Successful in 1m17s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m2s
CI / driver (push) Successful in 1m52s
driver / publish (push) Skipped
2026-12-02 21:31:41 +00:00
Christian Manivong 635607bfa4 chore(deps): require napalm-device-types 4.56.0, CI without the train pre-install
driver / lint (pull_request) Successful in 12s
driver / standard (pull_request) Successful in 14s
driver / lowest (pull_request) Successful in 25s
driver / test (3.12) (pull_request) Successful in 54s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 54s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 1m34s
driver / publish (pull_request) Skipped
2026-12-02 22:21:46 +01:00
Christian Manivong 52286e4009 Merge remote-tracking branch 'origin/feature/windows-logins-2895' into chore/merge-train-windows-depth
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 22s
driver / lowest (pull_request) Successful in 42s
driver / types (pull_request) Successful in 1m24s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / test (3.13) (pull_request) Successful in 1m16s
driver / build (pull_request) Successful in 35s
driver / security (pull_request) Successful in 1m23s
CI / driver (pull_request) Successful in 2m58s
driver / publish (pull_request) Skipped
2026-12-01 23:21:04 +01:00
Christian Manivong 2b0bfac4f7 refactor(logins): keep the member and session parses within complexity 10 (NetOrk/netork#2895)
_member hands its name and kind to _member_name and _is_group;
parse_login_sessions hands the audit check to _audited_logons and the
sessions to _sessions. No change in behaviour.
2026-12-01 23:20:36 +01:00
Christian Manivong 63a04c068b ci: test against the napalm-device-types train until it is released
driver / lint (pull_request) Failing after 4m17s
driver / standard (pull_request) Failing after 4m19s
driver / types (pull_request) Failing after 4m18s
driver / test (3.12) (pull_request) Failing after 4m21s
driver / test (3.13) (pull_request) Failing after 4m20s
driver / lowest (pull_request) Failing after 4m19s
driver / security (pull_request) Failing after 8m27s
driver / build (pull_request) Failing after 4m19s
CI / driver (pull_request) Failing after 12m50s
driver / publish (pull_request) Skipped
2026-12-01 23:20:25 +01:00
Christian Manivong a75be93c05 fix(harvest): the posture script belongs to SCRIPTS; imports sorted
driver / standard (pull_request) Failing after 14s
driver / lint (pull_request) Successful in 15s
driver / lowest (pull_request) Failing after 27s
driver / types (pull_request) Failing after 58s
driver / test (3.12) (pull_request) Failing after 53s
driver / test (3.13) (pull_request) Failing after 53s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 51s
CI / driver (pull_request) Failing after 1m47s
driver / publish (pull_request) Skipped
2026-12-01 13:23:31 +01:00
Christian Manivong c35b832db3 Merge remote-tracking branch 'origin/feature/windows-posture-2893' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:22:57 +01:00
Christian Manivong a15e24a38c fix(harvest): the Windows Update scripts belong to SCRIPTS, not RUNS 2026-12-01 13:19:42 +01:00
Christian Manivong 6fbf2f7ef6 Merge remote-tracking branch 'origin/feature/windows-update-2892' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:18:29 +01:00
Christian Manivong 08c97339bb style: sort the mixin imports of the merged streams 2026-12-01 13:18:29 +01:00
Christian Manivong e9e14cf316 Merge remote-tracking branch 'origin/feature/windows-repairs-2899' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tests/fixtures/synthetic/README.md
#	tools/harvest.py
2026-12-01 13:18:04 +01:00
Christian Manivong 48a1a5c14f Merge remote-tracking branch 'origin/feature/windows-events-2897' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:18:04 +01:00
Christian Manivong 998dcbb05f Merge remote-tracking branch 'origin/feature/windows-exposure' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:18:04 +01:00
Christian Manivong aa744d0309 Merge remote-tracking branch 'origin/feature/windows-logins-2895' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:18:03 +01:00
Christian Manivong c02cf1a0bb Merge remote-tracking branch 'origin/feature/windows-basics' into chore/merge-train-windows-depth
# Conflicts:
#	CHANGELOG.md
#	README.md
#	napalm_windows/windows.py
#	tools/harvest.py
2026-12-01 13:18:03 +01:00
Christian Manivong 9ff597a0da Merge remote-tracking branch 'origin/feature/windows-storage-2896' into chore/merge-train-windows-depth 2026-12-01 13:17:42 +01:00
Christian Manivong 4108581580 feat(updates): Windows Update -- search, pending updates, install in a SYSTEM task, history (NetOrk/netork#2892)
refresh_available_updates runs the Windows Update Agent's search against the
configured source and keeps its reading under HKLM\SOFTWARE\napalm-windows;
get_available_updates reads it back without a search, leaving out what the
history shows installed since, and raises PackageIndexMissing before the
first search. Each update carries its title, KB articles, CveIDs and
MsrcSeverity, and is named by its title without month, KB and version, so
next month's cumulative update keeps the name. Previews, feature upgrades and
drivers are left out.

apply_updates installs in a one-shot task running as SYSTEM, since Windows
refuses downloads and installs to a network logon. The task's script and the
exact UpdateID:revision chosen travel in the run's registry key; it searches
again, refuses what no longer matches exactly, what asks for input or has
unaccepted licence terms, installs nothing while a restart is pending and
never restarts. Its log is followed line by line; the next run sweeps what a
dead run left. get_scheduled_jobs shows these tasks as an application's.

get_update_history reads QueryHistory, one transaction per entry, with the
ClientApplicationID as requested_by.
2026-12-01 12:57:20 +01:00
Christian Manivong de6ab3c801 feat(logins): login accounts and console and Remote Desktop sessions (NetOrk/netork#2895)
get_login_accounts reads the host's own accounts (Get-LocalUser), their
last login and failed attempts from the account database, expiry and
lock, and whether each is an administrator (S-1-5-32-544, by SID) or may
log in over Remote Desktop (the logon right and its denial from
secedit, the host's fDenyTSConnections). groups lists the groups that
grant either, with every member, a domain's included. uid is the RID,
sid the SID. A domain controller's accounts are not read.

get_login_sessions reads logon events 4624 of type 2, 10 and 11 of the
last seven days from the Security log, ended by 4634/4647, an
administrator's two linked logons as one session. own_address is the
reading's own WinRM logon's address; records_since the log's oldest
event. A log without any logon raises LoginSessionsUnavailable.

Both scripts are in tools/harvest.py.
2026-12-01 12:55:49 +01:00
Christian Manivong 89a52db1a5 feat(log-sources): the event channels as the host's log sources (NetOrk/netork#2897)
WindowsLogSourcesMixin.get_log_sources lists every event channel that is
switched on and holds records (Get-WinEvent -ListLog *) as a source of kind
eventlog, named by its channel, with its .evtx file, size and last write.
Analytic and debug channels are left out. README and CHANGELOG describe the
services, host events and log sources readings.
2026-12-01 12:54:25 +01:00
Christian Manivong f8f46c133d refactor(host-status): the restart reasons as a table, within the complexity limit 2026-12-01 12:54:14 +01:00
Christian Manivong 891a31fe45 docs: the host basics in the README and CHANGELOG; harvest records their scripts 2026-12-01 12:53:46 +01:00
Christian Manivong 0df672fb7c feat(repairs): a caller's limit tightens a run's bound (NetOrk/netork#2899) 2026-12-01 12:53:17 +01:00
Christian Manivong 54b3c9b362 feat(host-status): restart required and automatic updates from Windows Update and the registry (NetOrk/netork#2891) 2026-12-01 12:53:17 +01:00
Christian Manivong 21a21383ff feat(host-events): the event log's shutdowns, crashes, hardware and disk errors (NetOrk/netork#2897)
WindowsHostEventsMixin.get_host_events(since=None) reads, in one script, three
bounded queries over the window: the System log's rare events (Kernel-Power 41,
EventLog 6008, WER-SystemErrorReporting 1001, WHEA-Logger 18, disk 7, Ntfs 55)
with their messages, its frequent ones (WHEA-Logger 19/47, disk 153, Service
Control Manager 7031/7034) and the Application log's crashes (Application Error
1000). Each query catches NoMatchingEventsFound; one that fails names its kinds
unread, one read up to its bound names them capped.
2026-12-01 12:53:13 +01:00
Christian Manivong 975eecf0cc Host firewall and Windows features (NetOrk/netork#2894, #2898)
get_host_firewall reads the Windows Firewall: the profiles' settings in
force, every enabled rule of the active policy with its filters read in
bulk and joined on InstanceID, and the profile of each connected
interface. get_windows_features lists the image's optional features
with their state from Win32_OptionalFeature. Both scripts are in the
harvest.
2026-12-01 12:51:41 +01:00
Christian Manivong 81c4df3159 feat(packages): installed programs from the machine-wide Uninstall keys (NetOrk/netork#2890) 2026-12-01 12:51:31 +01:00
Christian Manivong 7a5c607ae4 feat(storage): disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896)
WindowsStorageMixin implements napalm-device-types' HostStorageMixin, so
the host reports its storage and stays a host:

- get_disks: Get-PhysicalDisk with medium, bus, Windows' health and the
  Storage Spaces pool a disk is in; a Storage Spaces virtual disk is no
  physical disk.
- get_disk_smart: Get-StorageReliabilityCounter per disk (temperature,
  wear, power-on hours, uncorrected read and write errors). A counter
  that cannot be read is no counter, not an error; disks that report
  nothing are left out.
- get_disk_pools: Storage Spaces' pools.
- get_volumes: fixed volumes mounted at a drive letter or in a folder,
  with file system and health.

A disk whose medium Windows cannot tell and whose counters are empty (a
virtual disk, a RAID controller's logical disk) reads temperature -1 and
health "unknown". Every script probes its cmdlets first. The fixtures
are synthetic; the scripts are in harvest.py for the first real host.
2026-12-01 12:50:56 +01:00
Christian Manivong 84f6a3c3e3 feat(services): how a service's last run ended, trigger start and account (NetOrk/netork#2897)
get_services moves into WindowsServicesMixin and reads, beside state and start
mode, Win32_Service's ExitCode (1066 hands over to ServiceSpecificExitCode, 1077
is not started since boot), StartName and whether a TriggerInfo key starts the
service, as napalm-device-types' ServiceDict result, exit_code, trigger_start
and account.
2026-12-01 12:50:24 +01:00
Christian Manivong 169d88f7e5 feat(users): local accounts as UserDict, the RID as uid and the SID beside it (NetOrk/netork#2889) 2026-12-01 12:50:13 +01:00
Christian Manivong 0bbeebb7a7 feat(repairs): SFC, DISM and Defender runs through HostRepairMixin (NetOrk/netork#2899)
verify_system_files (sfc /verifyonly), check_component_store (DISM
/ScanHealth /English), update_antimalware_signatures (Update-MpSignature)
and scan_antimalware (Start-MpScan, quick or full), each one bounded PSRP
call streamed line by line through PsrpTransport.run_streaming. Native
tools run as a process read in their own encoding (sfc: UTF-16), and NULs
of UTF-16 read byte by byte are dropped. The exit code decides; a missing
tool or Defender says it is not available. sfc /scannow and DISM
/RestoreHealth stay undefined until a real host was tested.

tools/harvest.py --runs records the runs' output.
2026-12-01 12:49:37 +01:00
Christian Manivong a97e59c1e2 feat(processes): running processes from Win32_Process and Get-Process (NetOrk/netork#2889) 2026-12-01 12:49:17 +01:00
Christian Manivong 8ed5e0ed87 feat(identity): the SMBIOS identity from the CIM classes (NetOrk/netork#2888) 2026-12-01 12:47:57 +01:00
Christian Manivong 62bbc7df49 feat(posture): the security posture as the hardening reading (NetOrk/netork#2893)
get_hardening() reads Secure Boot, the TPM, BitLocker per volume, Defender,
the firewall profiles' state and virtualization-based security in one script,
each part caught on its own and each cmdlet probed with Get-Command first.
BitLocker through Win32_EncryptableVolume, never Get-BitLockerVolume: no
recovery password or key protector is read.
2026-12-01 12:47:25 +01:00
christianmanivong 977ddbd904 Merge pull request 'feat(power): restart and shut the host down with Restart-/Stop-Computer (NetOrk/netork#2841)' (#11) from feature/host-shutdown-2841 into main
driver / standard (push) Successful in 13s
driver / lint (push) Successful in 13s
driver / lowest (push) Successful in 25s
driver / types (push) Successful in 48s
driver / test (3.12) (push) Successful in 1m9s
driver / build (push) Successful in 24s
driver / test (3.13) (push) Successful in 56s
driver / security (push) Successful in 56s
CI / driver (push) Successful in 1m55s
driver / publish (push) Skipped
2026-11-29 21:58:22 +00:00
Christian Manivong d7511efd43 feat(power): restart and shut the host down with Restart-/Stop-Computer (NetOrk/netork#2841)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / test (3.13) (pull_request) Successful in 43s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 25s
driver / test (3.12) (pull_request) Successful in 55s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 56s
CI / driver (pull_request) Successful in 2m2s
driver / publish (pull_request) Skipped
reboot_host() and shutdown_host() run Restart-Computer and Stop-Computer
without -Force over the PSRP connection: Windows asks running programs
to close and refuses while other users are logged on. A refusal raises
RuntimeError with the host's answer; a connection the host drops before
answering counts as accepted, which PsrpTransport.run_last() reports.
2026-11-29 11:32:33 +01:00
christianmanivong 442541d30a Merge pull request 'feat(time-sync): w32time's servers and the time zone through TimeSyncMixin' (#10) from feature/time-sync-2367 into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m5s
driver / test (3.12) (push) Successful in 1m2s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m4s
CI / driver (push) Successful in 2m35s
driver / publish (push) Skipped
2026-11-11 14:51:44 +00:00
Christian Manivong 0b30ab00a5 feat(time-sync): w32time's servers and the time zone through TimeSyncMixin
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 26s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Successful in 2m23s
driver / publish (pull_request) Skipped
netOrk keeps one list of NTP servers and a time zone per site and aligns
a device that differs (NetOrk/netork#2360). A Windows host takes part
through w32time and its time zone, in one PowerShell script per read.

The servers and the mode are read from w32time's registry values, group
policy's first, not from w32tm /query /configuration, whose text is in
the host's language; synchronised is the leap indicator on the first
line of w32tm /query /status, which reads the same in any language. The
servers are written the way w32tm /config /manualpeerlist
/syncfromflags:manual writes them (NtpServer with 0x8, Type NTP),
followed by w32tm /config /update: no value passes a native command
line, whose quoting Windows PowerShell 5.1 mangles. A domain member that
takes its time from the domain hierarchy (NT5DS, AllSync) and a host
whose w32time comes from group policy refuse the write: their time is
set elsewhere, and a local write would be overridden or break the
domain's time.

Windows keeps a Windows zone, which stands for several IANA zones, so
Europe/Vienna written would read back as Europe/Berlin and the poll
would align the host forever. The IANA name written is kept beside it
in HKLM\SOFTWARE\napalm-windows and read back while the host is still
in that Windows zone. The zone is read from the registry, which
[TimeZoneInfo]::Local caches for the life of the remote session.

The zone table is now CLDR's windowsZones.xml (release 49) both ways,
generated by tools/windows_zones.py with tzdata's links and committed
with its source and checksum; nothing is fetched at runtime. CLDR's old
names (Asia/Calcutta) read as their current ones (Asia/Kolkata).

Writes the host already has are skipped. Needs napalm-device-types
4.35.0.

Refs NetOrk/netork#2367
2026-11-11 15:27:56 +01:00
christianmanivong 37708009a0 Merge pull request 'feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8)' (#9) from feature/scheduled-jobs into main
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 18s
driver / types (push) Successful in 1m7s
driver / test (3.12) (push) Successful in 1m2s
driver / test (3.13) (push) Successful in 58s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 27s
driver / security (push) Successful in 1m1s
CI / driver (push) Successful in 2m40s
driver / publish (push) Skipped
2026-11-03 08:20:27 +00:00
Christian Manivong 74a8c53c7c chore(scheduled-jobs): require napalm-device-types 4.27.0
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 55s
driver / test (3.13) (pull_request) Successful in 46s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m22s
driver / publish (pull_request) Skipped
4.26.0 went out with the sshd drop-in change; the scheduled-jobs
contract is in 4.27.0.
2026-11-03 08:36:00 +01:00
Christian Manivong a508b872b0 feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 15s
driver / test (3.12) (pull_request) Failing after 14s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 14s
driver / security (pull_request) Failing after 32s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Failing after 1m21s
driver / publish (pull_request) Skipped
netOrk shows and controls every scheduled job of a host; on Windows that
is the Task Scheduler. The driver now implements napalm-device-types'
ScheduledJobsMixin over PowerShell Remoting, one script per call as every
getter does.

get_scheduled_jobs reads every task with its run info in one script
(Get-ScheduledTask, Get-ScheduledTaskInfo) as task:<path><name>, its
triggers summarised. Tasks under \Microsoft\ are the platform's, others
the admin's: Windows does not record which software installed a task.
The time zone is mapped to IANA for the common Windows zones, else None.
A reading cut short, or holding fewer tasks than it counted, raises.

manage_scheduled_job switches the task's own flag or starts it;
Start-ScheduledTask returns once the task has started, so the result says
that and no more. A disabled task, or one that refuses a start on demand,
is not offered run.

put_scheduled_job registers an application's task \<name> in the root
folder from XML, so a create and a change write the whole definition the
same way: the command runs in cmd.exe /d /s /c, the principal is SYSTEM
or a local user without a stored password (S4U), and the cron expression
becomes triggers only where Task Scheduler can say it exactly; any other
shape is refused, naming why. The description keeps the job's name and
cron expression, so the reading gives back what was written, and the
digest also covers the triggers, so a change by hand is seen.
delete_scheduled_job unregisters such a task and no other. Every write
reads the task again first, and every value goes into PowerShell
single-quoted with its quotes doubled.

Requires napalm-device-types 4.26.0.

Closes #8
2026-11-03 05:49:12 +01:00
christianmanivong 581c2df5e8 Merge pull request 'fix: an unknown ARP age is -1.0, not 0.0' (#7) from fix/arp-unknown-age into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 15s
driver / types (push) Successful in 1m6s
driver / test (3.12) (push) Successful in 1m5s
driver / lowest (push) Successful in 32s
driver / test (3.13) (push) Successful in 57s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m12s
CI / driver (push) Successful in 2m50s
driver / publish (push) Skipped
2026-10-30 09:11:44 +00:00
Christian Manivong dacefaa606 fix: an unknown ARP age is -1.0, not 0.0
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 24s
driver / test (3.13) (pull_request) Successful in 48s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m32s
driver / publish (pull_request) Skipped
Get-NetNeighbor reports a state but no age, so get_arp_table reports
ARP_AGE_UNKNOWN instead of 0.0 ("confirmed just now").

NetOrk/netork#1327
2026-10-30 08:37:08 +01:00
christianmanivong 7c985acfad Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#6) from chore/python-312-floor into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 12s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 55s
driver / test (3.13) (push) Successful in 50s
driver / lowest (push) Successful in 25s
driver / build (push) Successful in 27s
driver / security (push) Successful in 1m2s
CI / driver (push) Successful in 2m24s
driver / publish (push) Skipped
2026-10-27 10:46:56 +00:00
Christian Manivong cd50d3c102 fix: the floor on napalm is 5.1 (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / test (3.12) (pull_request) Successful in 55s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 50s
driver / lowest (pull_request) Successful in 27s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m26s
CI / driver (pull_request) Successful in 2m51s
driver / publish (pull_request) Skipped
napalm 5.0 and older import pkg_resources, which a Python 3.12 venv no
longer has, so the lowest job failed on them.
2026-10-27 10:49:32 +01:00
Christian Manivong 15740f9e05 chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 20s
driver / lint (pull_request) Successful in 14s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Failing after 30s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m16s
CI / driver (pull_request) Failing after 2m57s
driver / publish (pull_request) Skipped
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:19:01 +01:00
86 changed files with 12867 additions and 86 deletions

No files matched your search

+175
View File
@@ -6,6 +6,181 @@ All notable changes to this driver. The format follows
## [Unreleased]
## [0.3.0] - 2026-12-03
### Changed
- Requires napalm-device-types 4.56.0, which declares the contracts below.
### Added
- Disks, pools, volumes and drive health without smartctl (NetOrk/netork#2896), through
napalm-device-types' `HostStorageMixin`, so the host stays a host. `get_disks` reads
`Get-PhysicalDisk` (model, serial, medium, NVMe, Windows' health, the Storage Spaces
pool a disk is in); `get_disk_smart` reads `Get-StorageReliabilityCounter` per disk
(temperature, wear, power-on hours, uncorrected read and write errors);
`get_disk_pools` reads Storage Spaces' pools; `get_volumes` the fixed volumes mounted at
a drive letter or in a folder, with file system and health. A disk whose counter cannot
be read -- the cmdlet needs an administrator, and virtual disks often have none -- has
no drive health rather than an error; a virtual disk or a RAID controller's logical
disk reads temperature -1 and health "unknown" instead of zeros and a "healthy" nobody
measured. A Storage Spaces virtual disk is not listed as a physical disk.
- The 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.
- Who can log in to the host and who did, for the access review (NetOrk/netork#2895):
napalm-device-types' `get_login_accounts` and `get_login_sessions`.
- `get_login_accounts` lists the host's own accounts (`Get-LocalUser`) with their
last login and failed attempts since it from the account database (source `sam`),
password and account expiry, and whether each is locked (disabled, expired or locked
out). Each says whether it is an administrator and whether it may log in over
Remote Desktop: found by SID, so a German "Administratoren" counts, and from the
Remote Desktop logon right and its denial (`secedit /export`) with the host's
Remote Desktop setting. `groups` lists the groups granting either, with every
member, a domain's groups and accounts by name. `uid` is the RID, `sid` the SID. A
domain controller's accounts are the directory's and are not listed.
- `get_login_sessions` lists the console and Remote Desktop logons of the last seven
days from the Security log, each with its account, address, start and end; never a
network logon, so neither the driver's own WinRM connection nor SMB access shows.
`records_since` says how far back the log reaches, and a host that does not audit
logons raises `LoginSessionsUnavailable` rather than reporting nobody.
- 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.
- What the event log recorded that says something is wrong with the host
(NetOrk/netork#2897): `get_host_events(since=None)`, napalm-device-types'
`HostEventsMixin`. Unexpected shutdowns (Kernel-Power 41, EventLog 6008), bugchecks
with their stop code (1001), fatal and corrected hardware errors (WHEA-Logger 18, 19,
47), disk and file system errors (disk 7 and 153, Ntfs 55), crashing programs
(Application Error 1000) and services that ended unexpectedly (Service Control
Manager 7031, 7034), over the last seven days by default, in one script of three
queries bounded by time and count. An empty log is no events, not an error
(`NoMatchingEventsFound` is caught); a query that fails names its kinds `unread`.
- The event channels as the host's log sources: `get_log_sources()` lists every channel
that is switched on and holds records as a source of kind `eventlog`, named by its
channel, with its `.evtx` file, size and last write (`Get-WinEvent -ListLog *`).
Analytic and debug channels are left out.
- `get_services()` says how each service's last run ended (`result`, `exit_code`, from
`Win32_Service.ExitCode` and `ServiceSpecificExitCode`), whether a trigger starts it
(`trigger_start`) and the account it runs as (`account`), so that an automatic service
that died is told from one stopped on purpose. It moves into `WindowsServicesMixin`.
- Repair runs (NetOrk/netork#2899), napalm-device-types' `HostRepairMixin`: checking the
system files (`sfc /verifyonly`) and the component store (`DISM /ScanHealth`), updating
Microsoft Defender's signatures and running a quick or full Defender scan. Each streams
the tool's output line by line as the host prints it and ends with the tool's exit
code; a failure names the tool's last lines. Each run has its own bound in time,
which a caller's `limit` can tighten. A host without Defender says so instead of
failing with an error. Repairing the system files or the component store is not offered
yet: both wait for a test on a real host. `PsrpTransport.run_streaming(script,
on_output, limit=...)` runs a long script, passing each output line on as it arrives and
stopping it past its limit.
- Windows Update (NetOrk/netork#2892). A refresh searches the update source the host is
configured for (Windows Update or its WSUS server) and keeps what it found on the host;
the pending updates are read from that, so a poll never waits minutes for a search.
Each pending update carries its title, KB articles, the CVEs it fixes and Microsoft's
severity rating, and is named so that next month's cumulative update keeps the same
name. Optional previews, feature upgrades and drivers are left out.
- Installing Windows updates (NetOrk/netork#2892): Windows does not let a remote session
install updates, so each run is a one-shot task running as SYSTEM. It installs only the
exact updates chosen, refuses one that is no longer offered, asks for input or has
licence terms not yet accepted, installs nothing while a restart is pending, and never
restarts the host. Its output arrives line by line; the task is deleted afterwards.
- The update history: what Windows Update installed or removed, when, which component
asked for it, and why it failed.
- The security posture as napalm-device-types' hardening reading (NetOrk/netork#2893):
`get_hardening()` reads, in one script, whether Secure Boot is on (or unsupported on a
BIOS boot), the TPM, BitLocker's protection per volume, Microsoft Defender (real-time
protection, its running mode, the signatures' age), whether each firewall profile is on,
and virtualization-based security. Each part is read on its own: a part that fails, or a
cmdlet the host does not have, is reported as not read, and a server without the
BitLocker feature as not installed. BitLocker is read through `Win32_EncryptableVolume`,
never `Get-BitLockerVolume`, so no recovery password or key protector is read. Nothing on
the host is changed.
- Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and
`shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin`
run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with
`-Force`: Windows asks running programs to close and refuses while other users are
logged on, a disconnected session included, instead of throwing away what they have
not saved. A refusal raises `RuntimeError` with the host's answer. Both cmdlets start
the shutdown and return, so no delay is needed before the session goes; a connection
the host drops before answering counts as accepted. `PsrpTransport.run_last(script)`
tells the two apart: `False` when the connection broke, `PowerShellError` when the
script wrote an error.
- Time sync: napalm-device-types' `TimeSyncMixin` (4.35.0), servers and zone
(NetOrk/netork#2367). `get_time_sync` reads w32time's `NtpServer` and `Type` from the
registry (group policy's first; `NoSync` has no servers), whether the clock is
synchronised (the leap indicator of `w32tm /query /status`) and the zone, in one
script. `configure_time_sync` writes the servers as `<server>,0x8` with `Type NTP`
and `w32tm /config /update`, starting a stopped Windows Time service, and the zone
with `Set-TimeZone`. A domain member that takes its time from the domain hierarchy
(`NT5DS`, `AllSync`) reports its configured servers and refuses the write, as does a
host whose w32time settings come from group policy. The IANA name written is kept in
`HKLM\SOFTWARE\napalm-windows` so it reads back as written; writes the host already
has are skipped.
- The time zone table is CLDR's `windowsZones.xml` (release 49), generated into
`napalm_windows/_windows_zones.py` by `tools/windows_zones.py` with tzdata's links,
both ways: every Windows zone reads as an IANA name, not only the common ones, and
every IANA zone CLDR maps has its Windows zone.
- Scheduled jobs: the Task Scheduler as napalm-device-types' `ScheduledJobsMixin` (#8).
`get_scheduled_jobs` reads every task with its last and next run in one script
(`Get-ScheduledTask`, `Get-ScheduledTaskInfo`) as `task:<path><name>`: a task under
`\Microsoft\` is the `platform`'s, any other the `admin`'s, and a task in the root
folder whose description starts with `napalm-scheduled-job: <name>` an `application`'s.
The time zone comes as an IANA name for the common Windows zones, else `None`.
`manage_scheduled_job` enables, disables (`Enable-`/`Disable-ScheduledTask`) or starts
one (`Start-ScheduledTask`, which returns once the task has started). `put_scheduled_job`
registers an application's task `\<name>` from XML: the command runs in
`cmd.exe /d /s /c`, `SYSTEM` or a local user without a stored password (S4U), and the
cron expression becomes triggers where Task Scheduler can express it exactly; any other
shape is refused, naming why. `delete_scheduled_job` unregisters it. Every write reads
the task again first and refuses over a change it did not see. Fixture synthetic.
### Changed
- The floor on napalm-device-types is 4.35.0, which declares the time sync contract.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
3.12 venv no longer has.
### Fixed
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now":
`Get-NetNeighbor` has a state but no age (NetOrk/netork#1327).
## [0.2.0] - 2026-10-23
The first release on PyPI.
+305 -2
View File
@@ -36,16 +36,319 @@ handshake once.
| `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
| `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
| `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
| `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
| `get_services` / `manage_service` | `Win32_Service` (with `ExitCode`, `StartName`) and the services' `TriggerInfo` registry keys, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType`. See *Services* |
| `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted |
| `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
| `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_host_events` | `Get-WinEvent -FilterXPath`, three bounded queries over the System and Application logs. See *Host events* |
| `get_log_sources` | `Get-WinEvent -ListLog *`: every event channel switched on and holding records, as kind `eventlog` |
| `refresh_available_updates` / `get_available_updates` | The Windows Update Agent's search (`Microsoft.Update.Session`), kept in the registry for the poll; the host's update history leaves out what was installed since. See *Windows Update* |
| `apply_updates` | A one-shot SYSTEM scheduled task that searches again and installs only the exact updates chosen; never restarts. See *Windows Update* |
| `get_update_history` | `IUpdateSearcher.QueryHistory`, the newest 300 entries |
| `get_hardening` | The security posture: `Confirm-SecureBootUEFI`, `Win32_Tpm`, `Win32_EncryptableVolume` (BitLocker, never `Get-BitLockerVolume`), `Get-MpComputerStatus`, `Get-NetFirewallProfile -PolicyStore ActiveStore`, `Win32_DeviceGuard`. See *Security posture* |
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
| `get_disks` / `get_disk_smart` / `get_disk_pools` / `get_volumes` | `Get-PhysicalDisk`, `Get-StorageReliabilityCounter`, `Get-StoragePool -IsPrimordial $false`, `Get-Volume` + `Get-Partition`; no smartctl. See *Storage* |
| `get_login_accounts` | `Get-LocalUser`, `Win32_UserProfile`, `WinNT:` (`BadPasswordAttempts`, `IsAccountLocked`, group members), `secedit /export /areas USER_RIGHTS`, `fDenyTSConnections`. See *Logins* |
| `get_login_sessions` | Security log 4624 (logon types 2, 10, 11), 4634/4647, bounded to seven days on the host. See *Logins* |
| `get_host_firewall` | The Windows Firewall under `windows` (no netfilter chains): the profiles' settings in force from `HNetCfg.FwPolicy2`, `AllowLocalFirewallRules` from `Get-NetFirewallProfile`, the enabled rules of `Get-NetFirewallRule -PolicyStore ActiveStore` with every filter read in bulk and joined on `InstanceID`, and `Get-NetConnectionProfile`. See *Host firewall* |
| `get_windows_features` | `Win32_OptionalFeature`: every optional feature of the image with its state, under DISM's names (`SMB1Protocol`, `MSMQ-Server`), a server's roles included |
| `verify_system_files`, `check_component_store`, `update_antimalware_signatures`, `scan_antimalware` | `sfc /verifyonly`, `DISM /Online /Cleanup-Image /ScanHealth /English`, `Update-MpSignature`, `Start-MpScan`; streamed runs, see *Repair runs* |
`running_kernel` carries the full build including the update revision
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
matching has to compare against.
Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
### Scheduled tasks
An application's own job is the task `\<name>` in the root folder, never a folder of
its own. Its description is `napalm-scheduled-job: <name> <description>` and a second
line `schedule: <cron expression>`, so the reading gives back the cron expression and
the command it was written with; its digest also covers the triggers, so triggers
changed by hand count as a change.
* **Command:** `cmd.exe /d /s /c "<command>"` — one line, as a Windows command line.
* **Principal:** `SYSTEM`, or a local user who runs it whether logged on or not
without a stored password (`S4U`). Such a run has no network credentials, and the
user needs the "Log on as a batch job" right.
* **Schedule:** a cron expression becomes triggers only where Task Scheduler can
express it exactly — daily, weekly on weekdays, or monthly on days of the month (in
some months); at one or more times, or evenly spaced times as one repetition
(`*/5`, `*/15 8-17`, `0 */6`), or one repeating trigger per hour (`*/7`); at most 48
triggers. `@reboot` is a boot trigger. Refused, naming why: both a day of the month
and a weekday (cron's *either* rule), a weekday together with days or months, and
times needing more than 48 triggers. A repetition counts elapsed time, so on the day
summer time starts or ends its later runs shift by the hour.
* **Not read:** which software installed a task (Windows does not record it), so a
vendor's updater is `admin`; and the days of a monthly trigger, which
`Get-ScheduledTask` does not expose.
### Time sync
napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
* **Servers** are w32time's `NtpServer` in order, without their `,0x` flags; group
policy's values (`HKLM\SOFTWARE\Policies\Microsoft\W32Time\Parameters`) win over
the local ones. `Type NoSync` has none. Written as `<server>,0x8` (client mode) with
`Type NTP` — what `w32tm /config /manualpeerlist /syncfromflags:manual` writes —
then `w32tm /config /update`; a stopped Windows Time service is started first.
* **Domain members** that take their time from the domain hierarchy (`Type NT5DS` or
`AllSync`) report the servers configured, and a write is refused: the domain sets
their time. So is a write where group policy sets w32time.
* **Synchronised** is the leap indicator of `w32tm /query /status` (`3` = not
synchronised); a stopped service is not synchronised. `daemon` is `w32time`.
* **Zone:** Windows keeps a Windows zone (`W. Europe Standard Time`), which stands
for several IANA zones. It is read as the zone CLDR names for it (`Europe/Berlin`)
and written with `Set-TimeZone` from CLDR's mapping
([`windowsZones.xml`](https://github.com/unicode-org/cldr/blob/release-49/common/supplemental/windowsZones.xml),
generated into `napalm_windows/_windows_zones.py` by `tools/windows_zones.py`,
never fetched at runtime). The IANA name written is kept in
`HKLM\SOFTWARE\napalm-windows` (`IanaTimeZone`) and read back while the host is
still in that Windows zone, so `Europe/Vienna` reads back as `Europe/Vienna`. A
zone with summer time switched off reads as `None`; writing the zone switches it
back on.
### Storage
napalm-device-types' `HostStorageMixin` (NetOrk/netork#2896): the host's storage without
the storage role, so the driver stays a host. Nothing is installed; everything comes from
the Storage module's CIM classes.
* **Disks** are `Get-PhysicalDisk` (`PhysicalDisk<N>` by `DeviceId`): model, serial,
medium, bus (NVMe is its own type), Windows' `HealthStatus` (`Healthy`, `Warning`,
`Unhealthy` -> `healthy`, `warning`, `failed`) and, for disks in a Storage Spaces pool,
the pool. A Storage Spaces virtual disk is no physical disk and is not listed.
* **Drive health** (`get_disk_smart`) is `Get-StorageReliabilityCounter` per disk:
temperature and its highest, wear (`percentage_used`, not for spinning disks), power-on
hours, uncorrected read and write errors. It needs an administrator; a disk whose
counter cannot be read, or whose counters are all empty, has no drive health and is
left out. Windows writes `0` for a temperature it does not have, which reads as none.
* **Unknown is not healthy.** A disk whose medium Windows cannot tell and whose counters
are empty -- a virtual disk, a RAID controller's logical disk -- reads temperature `-1`
and health `unknown`: Windows calls it `Healthy`, which only says it is attached.
`Warning` and `Unhealthy` are always passed on.
* **Pools** are Storage Spaces (`storage-spaces`; `Simple`, `Mirror`, `Parity` ->
`stripe`, `mirror`, `parity`). Size and allocation are raw capacity.
* **Volumes** are the fixed volumes mounted at a drive letter (`C:`) or in a folder
(`C:\Logs`), with file system and health; the EFI and recovery partitions are mounted
nowhere and left out.
A host without the Storage module reads as having none; an empty answer raises.
### Logins
napalm-device-types' login readings, for the access review (NetOrk/netork#2895). Both
are read-only, one script each, and take an administrator.
* **Accounts** are the host's own (`Get-LocalUser`; without it, not supported), not the
system's `DefaultAccount` and `WDAGUtilityAccount`. `uid` is the RID, `sid` the SID;
`shell` is empty, `home` the profile folder. The last login and the failed attempts
since it (`BadPasswordAttempts`) are the account database's, source `sam`; an account
is `locked` when disabled, expired or locked out. A domain controller's accounts are
the directory's and are not read.
* **Administrators and Remote Desktop** go by SID, so a German host's "Administratoren"
is found: `administrator` is membership of `S-1-5-32-544`; `remote_desktop` that the
host takes Remote Desktop logins (`fDenyTSConnections`, group policy first) and the
account holds `SeRemoteInteractiveLogonRight` without being denied it, through
itself, a local group, or a SID every local logon carries (Everyone, Local account).
`groups` lists the groups that grant either, with every member as the host names it,
a domain's groups included. secedit's export goes to a file under
`%SystemRoot%\Temp`, removed at once.
* **Sessions** are logon events 4624 of type 2 (console), 10 (Remote Desktop) and 11
(cached, at the console) of the last seven days, the newest 1000, as `tty` `console`
or `rdp`; network logons (type 3) are not, since every WinRM and SMB connection is
one. A person's account only: not `DWM-n` or `UMFD-n`. An administrator's two linked
logons are one session; the end is its logoff (4634, 4647). `own_address` is the
address of the reading's own WinRM logon, found by its logon ID, else the one client
connected to WinRM; its sessions are left out. `records_since` is the Security log's
oldest event: the log rotates by size, so a login before it is unknown. A log that
holds no logon, not even the reading's own, raises `LoginSessionsUnavailable`.
* **Not read:** OpenSSH for Windows logins and the Remote Desktop session manager's own
log (`TerminalServices-LocalSessionManager`); the domain's accounts.
### Host firewall
What the exposure chain holds a listening socket against (netork#2894). Read only: no
rule is ever written.
* **Profiles:** on or off, the default inbound and outbound action and "block all
incoming connections" as the firewall applies them (`HNetCfg.FwPolicy2`, group
policy over local), and whether group policy lets local rules apply.
* **Rules:** every enabled rule of the active policy (`ActiveStore`, local and group
policy merged), inbound and outbound, each with where it comes from (`local`,
`group_policy`, `dynamic`, ...). Its filters -- ports, addresses, program, service,
app package, interfaces, interface types, IPsec -- are read with one cmdlet per
filter kind (`Get-NetFirewallPortFilter -All`, ...) and joined on the rule's
`InstanceID`: one filter query per rule takes minutes on a few hundred rules.
Addresses become CIDRs (a mask as its prefix, a range as the networks covering it);
Windows' keywords (`LocalSubnet`, `RPC`) are kept in lower case. A block rule whose
filters did not all come back is left out rather than read as blocking everything.
* **Connections:** the profile of each connected interface, from its network's category
(`DomainAuthenticated` is the domain profile); None where that could not be read.
### Services
How a service's last run ended is `Win32_Service.ExitCode`, said in systemd's words
(napalm-device-types' `ServiceDict.result`): `0` is `success`, `1077` (never started
since boot: a demand-start service, or a delayed one in the minutes after boot) is no
result, `1066` is `exit-code` with the service's own `ServiceSpecificExitCode`, any
other code `exit-code` with that code (`1067`: the process ended without being
stopped). Both codes leave the host as `[int64]`: they are UInt32, and an HRESULT
would not fit `[int]`. `trigger_start` is a `TriggerInfo` key under the service, read
once for all of them; `account` is `StartName`.
### Host events
napalm-device-types' `HostEventsMixin`: what the event log recorded that says
something is wrong with the host, over the last seven days unless the caller names a
start. One script, three queries, each an XPath filter from the start on, newest
first and bounded by count:
| Query | Events | Bound |
|---|---|---|
| System, with messages | Kernel-Power 41 and EventLog 6008 (unexpected shutdown; 41's `BugcheckCode` as the stop code), WER-SystemErrorReporting 1001 (bugcheck, its stop code), WHEA-Logger 18 (fatal hardware error), disk 7 (bad block), Ntfs 55 (corruption, its volume) | 100 |
| System, without messages | WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (retried I/O, its disk), Service Control Manager 7031 and 7034 (a service that ended unexpectedly, its display name) | 500 |
| Application, without messages | Application Error 1000 (a program that crashed, its path) | 200 |
`Get-WinEvent` throws `NoMatchingEventsFound` when nothing matches; each query
catches it as no events, and any other failure costs only that query, whose kinds the
reading names `unread`. A query that returned its bound names its kinds `capped`.
What an event is about comes from its properties, never from its message, which is in
the host's language; messages are read only for the rare events (Windows formats them
slowly) and cut to 300 characters. Which of them is worth a warning is the
application's to say.
### Security posture
`get_hardening` fills the posture keys of napalm-device-types' `HardeningDict`
(NetOrk/netork#2893); what only a Linux kernel reports (security modules, crypto policy,
CPU vulnerabilities, command line) is `None`. One read-only script; each part is caught on
its own, and a part that failed, or a cmdlet the host lacks (probed with `Get-Command`),
is `None`: not read, never off. Most parts need an administrator.
* **Secure Boot:** `Confirm-SecureBootUEFI`; on a BIOS boot it throws
`PlatformNotSupportedException`, which reads `unsupported`, not `off`.
* **TPM:** `Win32_Tpm` (`root\cimv2\Security\MicrosoftTpm`): present, enabled, activated,
owned, the specification's version and the manufacturer's ID.
* **BitLocker:** `Win32_EncryptableVolume` (`root\cimv2\Security\MicrosoftVolumeEncryption`)
for each volume with a drive letter: protection (`on`, `off` -- also while suspended --
or `unknown`), conversion status and cipher; the OS volume is `system`. Never
`Get-BitLockerVolume`, whose objects carry the key protectors and recovery passwords:
the class's properties hold no secret. Where the class is missing the BitLocker feature
is not installed (Windows Server's default), reported as `installed: false`.
* **Defender:** `Get-MpComputerStatus`: engine and service, real-time protection, the
running mode (`Passive Mode`, `EDR Block Mode`: another product protects the host), the
signatures' date, age and version, tamper protection. Missing on Server Core without
the feature, and throwing where Defender is switched off for another product: `None`,
since no other product is judged.
* **Firewall profiles:** `Get-NetFirewallProfile -PolicyStore ActiveStore`, each profile on
or off after group policy. The rules are the host firewall reading's.
* **VBS:** `Win32_DeviceGuard` (`root\Microsoft\Windows\DeviceGuard`): off, configured or
running, and the services it runs (`credential_guard`, `hvci`, ...).
Nothing is changed on the host: no signature update, no scan, no setting.
Not yet: packages, Windows Update, health metrics, Hyper-V.
### Host basics
* **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.
Not yet: Windows Update, health metrics, Hyper-V.
### Windows Update
napalm-device-types' `UpdateMixin`, through the Windows Update Agent's COM API.
* **The search is the refresh.** `refresh_available_updates` searches the source the
host is configured for -- Windows Update, or the WSUS server group policy names --
for `IsInstalled=0 and IsHidden=0 and Type='Software'`: no drivers. A search takes
minutes, so the poll never runs one. It keeps its reading under
`HKLM\SOFTWARE\napalm-windows\WindowsUpdate` (only administrators and SYSTEM may write
there), and `get_available_updates` reads that back, leaving out what the host's
history shows installed since. Before the first search it raises
`PackageIndexMissing`, which a refresh cures.
* **Names.** An update is named by what it keeps from month to month: its title without
the month, the KB article and the version, as a package name
(`Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems`).
Next month's cumulative update takes this one's place under the same name, so the time
a host has waited for it is not reset each month. `new_version` and `advisories` are
its KB articles, `cves` its `CveIDs`, `vendor_severity` its `MsrcSeverity`, `title`
its title. A security update, a definition update or one naming CVEs is `security`;
another classified one is not.
* **Not pending:** optional updates (`BrowseOnly`: previews Windows does not install by
itself) and feature upgrades -- this path installs neither.
* **Installing** (`apply_updates`). Windows refuses a download or an install to a
network logon (`E_ACCESSDENIED`), so a run is a one-shot task
`\napalm-windows\update-run-<id>` running as SYSTEM. Its script and the exact updates
chosen (`<UpdateID>:<revision>`, those the last search found under each name) go into
the run's registry key; no file is written. The task searches again and refuses, by
name, an update no longer offered under that ID and revision, one offered twice, one
that asks for input while it installs (`CanRequestUserInput`), and one whose licence
terms the host has not accepted; while a restart is pending it installs nothing. It
never restarts the host. The driver follows the run's log every 5 seconds and hands each
line to `log`, then deletes the task and the key. The tasks and keys of runs whose
connection died are deleted by the next run, which refuses to start while one is still
installing; a run followed for 25 minutes is left to finish on the host. The task names
itself to Windows Update as `napalm-windows`, which the history's `requested_by`
shows. `get_scheduled_jobs` reports these tasks as an application's, offering nothing.
* **History** (`get_update_history`): `QueryHistory`, newest 300 entries, one transaction
each; `requested_by` is the `ClientApplicationID` (`UpdateOrchestrator`,
`AutomaticUpdates`, `napalm-windows`), `error` the result and its HRESULT.
Not yet: packages, health metrics, Hyper-V.
See netork#300 for the plan.
### Repair runs
napalm-device-types' `HostRepairMixin` (NetOrk/netork#2899): a fixed catalog of runs, one
method each, so an application can start these and nothing else.
| Run | Tool | Bound (a caller's `limit` can tighten it) |
|---|---|---|
| `verify_system_files` | `sfc /verifyonly` (changes nothing) | 1 h |
| `check_component_store` | `DISM /Online /Cleanup-Image /ScanHealth /English` (changes nothing) | 1 h |
| `update_antimalware_signatures` | `Update-MpSignature`, with the signature version before and after | 15 min |
| `scan_antimalware(quick=True)` | `Start-MpScan -ScanType QuickScan` (`FullScan` with `quick=False`), with what it detected | 1 h (4 h) |
* **Not offered yet:** `repair_system_files` (`sfc /scannow`), which may fail to start the
repair service (TrustedInstaller) in a remote session, and `repair_component_store`
(`DISM /RestoreHealth`), which needs a repair source WSUS-managed hosts often lack
(`0x800f081f`). Both wait for a test on a real host.
* **Transport:** one bounded PSRP call per run (`PsrpTransport.run_streaming`): each line
reaches the caller's `log` as the host prints it, and a run past its limit is stopped.
The tools run as the connection's administrator; the SYSTEM scheduled task is where a
tool would move should a real host show it needs SYSTEM.
* **Output:** `sfc` writes UTF-16 to a redirected stdout and is read as such; DISM runs
with `/English` in the OEM code page. Text that still arrives as UTF-16 read byte by byte
loses its NULs. The exit code decides: 0 succeeds, any other fails with the tool's last
lines (an HRESULT in hex). A check that finds damage can still end with 0: the verdict is
in its output, `sfc`'s in the host's language.
* **Defender** runs only where `Get-Command` finds its cmdlets; elsewhere (another
antivirus, a Server without the feature) the run fails with "not available on this
host". A scan's detections are handled as Defender is set to handle them.
* None of them restarts the host or creates a restore point.
## Preparing a host
WinRM is on by default on Windows Server; on Windows 10/11 run
+24
View File
@@ -0,0 +1,24 @@
"""What every script and every parse of this driver shares: quoting and the JSON quirk."""
from __future__ import annotations
from typing import Any
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
def _as_list(value: Any) -> list[Any]:
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
if value is None:
return []
if isinstance(value, list):
return value
return [value]
def _ps_quote(value: str) -> str:
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
for q in _PS_SINGLE_QUOTES:
value = value.replace(q, q + q)
return f"'{value}'"
+18
View File
@@ -0,0 +1,18 @@
"""One reading script's JSON object, which the host readings of this driver share."""
from __future__ import annotations
import json
from typing import Any
def json_object(out: str, what: str) -> dict[str, Any]:
"""*out*, a script's ``ConvertTo-Json`` of one object, parsed.
:raises ValueError: when it is empty or no object, naming *what* was read.
"""
out = out.strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError(f"the {what} reading came back empty")
return raw
+732
View File
@@ -0,0 +1,732 @@
"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.
Source: CLDR release-49, common/supplemental/windowsZones.xml
(sha256 5f902f94106a396cb7774f0b0e1ca4dfecb686494045350c0b4935d378e3913b),
with the link lines of the IANA time zone database 2026e (tzdata.zi).
"""
WINDOWS_TO_IANA: dict[str, str] = {
"AUS Central Standard Time": "Australia/Darwin",
"AUS Eastern Standard Time": "Australia/Sydney",
"Afghanistan Standard Time": "Asia/Kabul",
"Alaskan Standard Time": "America/Anchorage",
"Alberta Standard Time": "America/Edmonton",
"Aleutian Standard Time": "America/Adak",
"Altai Standard Time": "Asia/Barnaul",
"Arab Standard Time": "Asia/Riyadh",
"Arabian Standard Time": "Asia/Dubai",
"Arabic Standard Time": "Asia/Baghdad",
"Argentina Standard Time": "America/Argentina/Buenos_Aires",
"Astrakhan Standard Time": "Europe/Astrakhan",
"Atlantic Standard Time": "America/Halifax",
"Aus Central W. Standard Time": "Australia/Eucla",
"Azerbaijan Standard Time": "Asia/Baku",
"Azores Standard Time": "Atlantic/Azores",
"Bahia Standard Time": "America/Bahia",
"Bangladesh Standard Time": "Asia/Dhaka",
"Belarus Standard Time": "Europe/Minsk",
"Bougainville Standard Time": "Pacific/Bougainville",
"British Columbia Standard Time": "America/Vancouver",
"Canada Central Standard Time": "America/Regina",
"Cape Verde Standard Time": "Atlantic/Cape_Verde",
"Caucasus Standard Time": "Asia/Yerevan",
"Cen. Australia Standard Time": "Australia/Adelaide",
"Central America Standard Time": "America/Guatemala",
"Central Asia Standard Time": "Asia/Bishkek",
"Central Brazilian Standard Time": "America/Cuiaba",
"Central Europe Standard Time": "Europe/Budapest",
"Central European Standard Time": "Europe/Warsaw",
"Central Pacific Standard Time": "Pacific/Guadalcanal",
"Central Standard Time": "America/Chicago",
"Central Standard Time (Mexico)": "America/Mexico_City",
"Chatham Islands Standard Time": "Pacific/Chatham",
"China Standard Time": "Asia/Shanghai",
"Cuba Standard Time": "America/Havana",
"Dateline Standard Time": "Etc/GMT+12",
"E. Africa Standard Time": "Africa/Nairobi",
"E. Australia Standard Time": "Australia/Brisbane",
"E. Europe Standard Time": "Europe/Chisinau",
"E. South America Standard Time": "America/Sao_Paulo",
"Easter Island Standard Time": "Pacific/Easter",
"Eastern Standard Time": "America/New_York",
"Eastern Standard Time (Mexico)": "America/Cancun",
"Egypt Standard Time": "Africa/Cairo",
"Ekaterinburg Standard Time": "Asia/Yekaterinburg",
"FLE Standard Time": "Europe/Kyiv",
"Fiji Standard Time": "Pacific/Fiji",
"GMT Standard Time": "Europe/London",
"GTB Standard Time": "Europe/Bucharest",
"Georgian Standard Time": "Asia/Tbilisi",
"Greenland Standard Time": "America/Nuuk",
"Greenwich Standard Time": "Atlantic/Reykjavik",
"Haiti Standard Time": "America/Port-au-Prince",
"Hawaiian Standard Time": "Pacific/Honolulu",
"India Standard Time": "Asia/Kolkata",
"Iran Standard Time": "Asia/Tehran",
"Israel Standard Time": "Asia/Jerusalem",
"Jordan Standard Time": "Asia/Amman",
"Kaliningrad Standard Time": "Europe/Kaliningrad",
"Korea Standard Time": "Asia/Seoul",
"Libya Standard Time": "Africa/Tripoli",
"Line Islands Standard Time": "Pacific/Kiritimati",
"Lord Howe Standard Time": "Australia/Lord_Howe",
"Magadan Standard Time": "Asia/Magadan",
"Magallanes Standard Time": "America/Punta_Arenas",
"Manitoba Standard Time": "America/Winnipeg",
"Marquesas Standard Time": "Pacific/Marquesas",
"Mauritius Standard Time": "Indian/Mauritius",
"Middle East Standard Time": "Asia/Beirut",
"Montevideo Standard Time": "America/Montevideo",
"Morocco Standard Time": "Africa/Casablanca",
"Mountain Standard Time": "America/Denver",
"Mountain Standard Time (Mexico)": "America/Mazatlan",
"Myanmar Standard Time": "Asia/Yangon",
"N. Central Asia Standard Time": "Asia/Novosibirsk",
"Namibia Standard Time": "Africa/Windhoek",
"Nepal Standard Time": "Asia/Kathmandu",
"New Zealand Standard Time": "Pacific/Auckland",
"Newfoundland Standard Time": "America/St_Johns",
"Norfolk Standard Time": "Pacific/Norfolk",
"North Asia East Standard Time": "Asia/Irkutsk",
"North Asia Standard Time": "Asia/Krasnoyarsk",
"North Korea Standard Time": "Asia/Pyongyang",
"Omsk Standard Time": "Asia/Omsk",
"Pacific SA Standard Time": "America/Santiago",
"Pacific Standard Time": "America/Los_Angeles",
"Pacific Standard Time (Mexico)": "America/Tijuana",
"Pakistan Standard Time": "Asia/Karachi",
"Paraguay Standard Time": "America/Asuncion",
"Qyzylorda Standard Time": "Asia/Qyzylorda",
"Romance Standard Time": "Europe/Paris",
"Russia Time Zone 10": "Asia/Srednekolymsk",
"Russia Time Zone 11": "Asia/Kamchatka",
"Russia Time Zone 3": "Europe/Samara",
"Russian Standard Time": "Europe/Moscow",
"SA Eastern Standard Time": "America/Cayenne",
"SA Pacific Standard Time": "America/Bogota",
"SA Western Standard Time": "America/La_Paz",
"SE Asia Standard Time": "Asia/Bangkok",
"Saint Pierre Standard Time": "America/Miquelon",
"Sakhalin Standard Time": "Asia/Sakhalin",
"Samoa Standard Time": "Pacific/Apia",
"Sao Tome Standard Time": "Africa/Sao_Tome",
"Saratov Standard Time": "Europe/Saratov",
"Singapore Standard Time": "Asia/Singapore",
"South Africa Standard Time": "Africa/Johannesburg",
"South Sudan Standard Time": "Africa/Juba",
"Sri Lanka Standard Time": "Asia/Colombo",
"Sudan Standard Time": "Africa/Khartoum",
"Syria Standard Time": "Asia/Damascus",
"Taipei Standard Time": "Asia/Taipei",
"Tasmania Standard Time": "Australia/Hobart",
"Tocantins Standard Time": "America/Araguaina",
"Tokyo Standard Time": "Asia/Tokyo",
"Tomsk Standard Time": "Asia/Tomsk",
"Tonga Standard Time": "Pacific/Tongatapu",
"Transbaikal Standard Time": "Asia/Chita",
"Turkey Standard Time": "Europe/Istanbul",
"Turks And Caicos Standard Time": "America/Grand_Turk",
"US Eastern Standard Time": "America/Indiana/Indianapolis",
"US Mountain Standard Time": "America/Phoenix",
"UTC": "Etc/UTC",
"UTC+12": "Etc/GMT-12",
"UTC+13": "Etc/GMT-13",
"UTC-02": "Etc/GMT+2",
"UTC-08": "Etc/GMT+8",
"UTC-09": "Etc/GMT+9",
"UTC-11": "Etc/GMT+11",
"Ulaanbaatar Standard Time": "Asia/Ulaanbaatar",
"Venezuela Standard Time": "America/Caracas",
"Vladivostok Standard Time": "Asia/Vladivostok",
"Volgograd Standard Time": "Europe/Volgograd",
"W. Australia Standard Time": "Australia/Perth",
"W. Central Africa Standard Time": "Africa/Lagos",
"W. Europe Standard Time": "Europe/Berlin",
"W. Mongolia Standard Time": "Asia/Hovd",
"West Asia Standard Time": "Asia/Tashkent",
"West Bank Standard Time": "Asia/Hebron",
"West Pacific Standard Time": "Pacific/Port_Moresby",
"Yakutsk Standard Time": "Asia/Yakutsk",
"Yukon Standard Time": "America/Whitehorse",
}
IANA_TO_WINDOWS: dict[str, str] = {
"Africa/Abidjan": "Greenwich Standard Time",
"Africa/Accra": "Greenwich Standard Time",
"Africa/Addis_Ababa": "E. Africa Standard Time",
"Africa/Algiers": "W. Central Africa Standard Time",
"Africa/Asmara": "E. Africa Standard Time",
"Africa/Asmera": "E. Africa Standard Time",
"Africa/Bamako": "Greenwich Standard Time",
"Africa/Bangui": "W. Central Africa Standard Time",
"Africa/Banjul": "Greenwich Standard Time",
"Africa/Bissau": "Greenwich Standard Time",
"Africa/Blantyre": "South Africa Standard Time",
"Africa/Brazzaville": "W. Central Africa Standard Time",
"Africa/Bujumbura": "South Africa Standard Time",
"Africa/Cairo": "Egypt Standard Time",
"Africa/Casablanca": "Morocco Standard Time",
"Africa/Ceuta": "Romance Standard Time",
"Africa/Conakry": "Greenwich Standard Time",
"Africa/Dakar": "Greenwich Standard Time",
"Africa/Dar_es_Salaam": "E. Africa Standard Time",
"Africa/Djibouti": "E. Africa Standard Time",
"Africa/Douala": "W. Central Africa Standard Time",
"Africa/El_Aaiun": "Morocco Standard Time",
"Africa/Freetown": "Greenwich Standard Time",
"Africa/Gaborone": "South Africa Standard Time",
"Africa/Harare": "South Africa Standard Time",
"Africa/Johannesburg": "South Africa Standard Time",
"Africa/Juba": "South Sudan Standard Time",
"Africa/Kampala": "E. Africa Standard Time",
"Africa/Khartoum": "Sudan Standard Time",
"Africa/Kigali": "South Africa Standard Time",
"Africa/Kinshasa": "W. Central Africa Standard Time",
"Africa/Lagos": "W. Central Africa Standard Time",
"Africa/Libreville": "W. Central Africa Standard Time",
"Africa/Lome": "Greenwich Standard Time",
"Africa/Luanda": "W. Central Africa Standard Time",
"Africa/Lubumbashi": "South Africa Standard Time",
"Africa/Lusaka": "South Africa Standard Time",
"Africa/Malabo": "W. Central Africa Standard Time",
"Africa/Maputo": "South Africa Standard Time",
"Africa/Maseru": "South Africa Standard Time",
"Africa/Mbabane": "South Africa Standard Time",
"Africa/Mogadishu": "E. Africa Standard Time",
"Africa/Monrovia": "Greenwich Standard Time",
"Africa/Nairobi": "E. Africa Standard Time",
"Africa/Ndjamena": "W. Central Africa Standard Time",
"Africa/Niamey": "W. Central Africa Standard Time",
"Africa/Nouakchott": "Greenwich Standard Time",
"Africa/Ouagadougou": "Greenwich Standard Time",
"Africa/Porto-Novo": "W. Central Africa Standard Time",
"Africa/Sao_Tome": "Sao Tome Standard Time",
"Africa/Timbuktu": "Greenwich Standard Time",
"Africa/Tripoli": "Libya Standard Time",
"Africa/Tunis": "W. Central Africa Standard Time",
"Africa/Windhoek": "Namibia Standard Time",
"America/Adak": "Aleutian Standard Time",
"America/Anchorage": "Alaskan Standard Time",
"America/Anguilla": "SA Western Standard Time",
"America/Antigua": "SA Western Standard Time",
"America/Araguaina": "Tocantins Standard Time",
"America/Argentina/Buenos_Aires": "Argentina Standard Time",
"America/Argentina/Catamarca": "Argentina Standard Time",
"America/Argentina/Cordoba": "Argentina Standard Time",
"America/Argentina/Jujuy": "Argentina Standard Time",
"America/Argentina/La_Rioja": "Argentina Standard Time",
"America/Argentina/Mendoza": "Argentina Standard Time",
"America/Argentina/Rio_Gallegos": "Argentina Standard Time",
"America/Argentina/Salta": "Argentina Standard Time",
"America/Argentina/San_Juan": "Argentina Standard Time",
"America/Argentina/San_Luis": "Argentina Standard Time",
"America/Argentina/Tucuman": "Argentina Standard Time",
"America/Argentina/Ushuaia": "Argentina Standard Time",
"America/Aruba": "SA Western Standard Time",
"America/Asuncion": "Paraguay Standard Time",
"America/Atikokan": "SA Pacific Standard Time",
"America/Atka": "Aleutian Standard Time",
"America/Bahia": "Bahia Standard Time",
"America/Bahia_Banderas": "Central Standard Time (Mexico)",
"America/Barbados": "SA Western Standard Time",
"America/Belem": "SA Eastern Standard Time",
"America/Belize": "Central America Standard Time",
"America/Blanc-Sablon": "SA Western Standard Time",
"America/Boa_Vista": "SA Western Standard Time",
"America/Bogota": "SA Pacific Standard Time",
"America/Boise": "Mountain Standard Time",
"America/Buenos_Aires": "Argentina Standard Time",
"America/Cambridge_Bay": "Mountain Standard Time",
"America/Campo_Grande": "Central Brazilian Standard Time",
"America/Cancun": "Eastern Standard Time (Mexico)",
"America/Caracas": "Venezuela Standard Time",
"America/Catamarca": "Argentina Standard Time",
"America/Cayenne": "SA Eastern Standard Time",
"America/Cayman": "SA Pacific Standard Time",
"America/Chicago": "Central Standard Time",
"America/Chihuahua": "Central Standard Time (Mexico)",
"America/Ciudad_Juarez": "Mountain Standard Time",
"America/Coral_Harbour": "SA Pacific Standard Time",
"America/Cordoba": "Argentina Standard Time",
"America/Costa_Rica": "Central America Standard Time",
"America/Coyhaique": "Magallanes Standard Time",
"America/Creston": "US Mountain Standard Time",
"America/Cuiaba": "Central Brazilian Standard Time",
"America/Curacao": "SA Western Standard Time",
"America/Danmarkshavn": "Greenwich Standard Time",
"America/Dawson": "Yukon Standard Time",
"America/Dawson_Creek": "US Mountain Standard Time",
"America/Denver": "Mountain Standard Time",
"America/Detroit": "Eastern Standard Time",
"America/Dominica": "SA Western Standard Time",
"America/Edmonton": "Alberta Standard Time",
"America/Eirunepe": "SA Pacific Standard Time",
"America/El_Salvador": "Central America Standard Time",
"America/Ensenada": "Pacific Standard Time (Mexico)",
"America/Fort_Nelson": "US Mountain Standard Time",
"America/Fortaleza": "SA Eastern Standard Time",
"America/Glace_Bay": "Atlantic Standard Time",
"America/Godthab": "Greenland Standard Time",
"America/Goose_Bay": "Atlantic Standard Time",
"America/Grand_Turk": "Turks And Caicos Standard Time",
"America/Grenada": "SA Western Standard Time",
"America/Guadeloupe": "SA Western Standard Time",
"America/Guatemala": "Central America Standard Time",
"America/Guayaquil": "SA Pacific Standard Time",
"America/Guyana": "SA Western Standard Time",
"America/Halifax": "Atlantic Standard Time",
"America/Havana": "Cuba Standard Time",
"America/Hermosillo": "US Mountain Standard Time",
"America/Indiana/Indianapolis": "US Eastern Standard Time",
"America/Indiana/Knox": "Central Standard Time",
"America/Indiana/Marengo": "US Eastern Standard Time",
"America/Indiana/Petersburg": "Eastern Standard Time",
"America/Indiana/Tell_City": "Central Standard Time",
"America/Indiana/Vevay": "US Eastern Standard Time",
"America/Indiana/Vincennes": "Eastern Standard Time",
"America/Indiana/Winamac": "Eastern Standard Time",
"America/Indianapolis": "US Eastern Standard Time",
"America/Inuvik": "Alberta Standard Time",
"America/Iqaluit": "Eastern Standard Time",
"America/Jamaica": "SA Pacific Standard Time",
"America/Jujuy": "Argentina Standard Time",
"America/Juneau": "Alaskan Standard Time",
"America/Kentucky/Louisville": "Eastern Standard Time",
"America/Kentucky/Monticello": "Eastern Standard Time",
"America/Knox_IN": "Central Standard Time",
"America/Kralendijk": "SA Western Standard Time",
"America/La_Paz": "SA Western Standard Time",
"America/Lima": "SA Pacific Standard Time",
"America/Los_Angeles": "Pacific Standard Time",
"America/Louisville": "Eastern Standard Time",
"America/Lower_Princes": "SA Western Standard Time",
"America/Maceio": "SA Eastern Standard Time",
"America/Managua": "Central America Standard Time",
"America/Manaus": "SA Western Standard Time",
"America/Marigot": "SA Western Standard Time",
"America/Martinique": "SA Western Standard Time",
"America/Matamoros": "Central Standard Time",
"America/Mazatlan": "Mountain Standard Time (Mexico)",
"America/Mendoza": "Argentina Standard Time",
"America/Menominee": "Central Standard Time",
"America/Merida": "Central Standard Time (Mexico)",
"America/Metlakatla": "Alaskan Standard Time",
"America/Mexico_City": "Central Standard Time (Mexico)",
"America/Miquelon": "Saint Pierre Standard Time",
"America/Moncton": "Atlantic Standard Time",
"America/Monterrey": "Central Standard Time (Mexico)",
"America/Montevideo": "Montevideo Standard Time",
"America/Montreal": "Eastern Standard Time",
"America/Montserrat": "SA Western Standard Time",
"America/Nassau": "Eastern Standard Time",
"America/New_York": "Eastern Standard Time",
"America/Nipigon": "Eastern Standard Time",
"America/Nome": "Alaskan Standard Time",
"America/Noronha": "UTC-02",
"America/North_Dakota/Beulah": "Central Standard Time",
"America/North_Dakota/Center": "Central Standard Time",
"America/North_Dakota/New_Salem": "Central Standard Time",
"America/Nuuk": "Greenland Standard Time",
"America/Ojinaga": "Central Standard Time",
"America/Panama": "SA Pacific Standard Time",
"America/Pangnirtung": "Eastern Standard Time",
"America/Paramaribo": "SA Eastern Standard Time",
"America/Phoenix": "US Mountain Standard Time",
"America/Port-au-Prince": "Haiti Standard Time",
"America/Port_of_Spain": "SA Western Standard Time",
"America/Porto_Acre": "SA Pacific Standard Time",
"America/Porto_Velho": "SA Western Standard Time",
"America/Puerto_Rico": "SA Western Standard Time",
"America/Punta_Arenas": "Magallanes Standard Time",
"America/Rainy_River": "Manitoba Standard Time",
"America/Rankin_Inlet": "Central Standard Time",
"America/Recife": "SA Eastern Standard Time",
"America/Regina": "Canada Central Standard Time",
"America/Resolute": "Central Standard Time",
"America/Rio_Branco": "SA Pacific Standard Time",
"America/Santa_Isabel": "Pacific Standard Time (Mexico)",
"America/Santarem": "SA Eastern Standard Time",
"America/Santiago": "Pacific SA Standard Time",
"America/Santo_Domingo": "SA Western Standard Time",
"America/Sao_Paulo": "E. South America Standard Time",
"America/Scoresbysund": "Azores Standard Time",
"America/Shiprock": "Mountain Standard Time",
"America/Sitka": "Alaskan Standard Time",
"America/St_Barthelemy": "SA Western Standard Time",
"America/St_Johns": "Newfoundland Standard Time",
"America/St_Kitts": "SA Western Standard Time",
"America/St_Lucia": "SA Western Standard Time",
"America/St_Thomas": "SA Western Standard Time",
"America/St_Vincent": "SA Western Standard Time",
"America/Swift_Current": "Canada Central Standard Time",
"America/Tegucigalpa": "Central America Standard Time",
"America/Thule": "Atlantic Standard Time",
"America/Thunder_Bay": "Eastern Standard Time",
"America/Tijuana": "Pacific Standard Time (Mexico)",
"America/Toronto": "Eastern Standard Time",
"America/Tortola": "SA Western Standard Time",
"America/Vancouver": "British Columbia Standard Time",
"America/Virgin": "SA Western Standard Time",
"America/Whitehorse": "Yukon Standard Time",
"America/Winnipeg": "Manitoba Standard Time",
"America/Yakutat": "Alaskan Standard Time",
"America/Yellowknife": "Alberta Standard Time",
"Antarctica/Casey": "Central Pacific Standard Time",
"Antarctica/Davis": "SE Asia Standard Time",
"Antarctica/DumontDUrville": "West Pacific Standard Time",
"Antarctica/Macquarie": "Tasmania Standard Time",
"Antarctica/Mawson": "West Asia Standard Time",
"Antarctica/McMurdo": "New Zealand Standard Time",
"Antarctica/Palmer": "SA Eastern Standard Time",
"Antarctica/Rothera": "SA Eastern Standard Time",
"Antarctica/South_Pole": "New Zealand Standard Time",
"Antarctica/Syowa": "E. Africa Standard Time",
"Antarctica/Vostok": "Central Asia Standard Time",
"Arctic/Longyearbyen": "W. Europe Standard Time",
"Asia/Aden": "Arab Standard Time",
"Asia/Almaty": "West Asia Standard Time",
"Asia/Amman": "Jordan Standard Time",
"Asia/Anadyr": "Russia Time Zone 11",
"Asia/Aqtau": "West Asia Standard Time",
"Asia/Aqtobe": "West Asia Standard Time",
"Asia/Ashgabat": "West Asia Standard Time",
"Asia/Ashkhabad": "West Asia Standard Time",
"Asia/Atyrau": "West Asia Standard Time",
"Asia/Baghdad": "Arabic Standard Time",
"Asia/Bahrain": "Arab Standard Time",
"Asia/Baku": "Azerbaijan Standard Time",
"Asia/Bangkok": "SE Asia Standard Time",
"Asia/Barnaul": "Altai Standard Time",
"Asia/Beirut": "Middle East Standard Time",
"Asia/Bishkek": "Central Asia Standard Time",
"Asia/Brunei": "Singapore Standard Time",
"Asia/Calcutta": "India Standard Time",
"Asia/Chita": "Transbaikal Standard Time",
"Asia/Choibalsan": "Ulaanbaatar Standard Time",
"Asia/Chongqing": "China Standard Time",
"Asia/Chungking": "China Standard Time",
"Asia/Colombo": "Sri Lanka Standard Time",
"Asia/Dacca": "Bangladesh Standard Time",
"Asia/Damascus": "Syria Standard Time",
"Asia/Dhaka": "Bangladesh Standard Time",
"Asia/Dili": "Tokyo Standard Time",
"Asia/Dubai": "Arabian Standard Time",
"Asia/Dushanbe": "West Asia Standard Time",
"Asia/Famagusta": "GTB Standard Time",
"Asia/Gaza": "West Bank Standard Time",
"Asia/Harbin": "China Standard Time",
"Asia/Hebron": "West Bank Standard Time",
"Asia/Ho_Chi_Minh": "SE Asia Standard Time",
"Asia/Hong_Kong": "China Standard Time",
"Asia/Hovd": "W. Mongolia Standard Time",
"Asia/Irkutsk": "North Asia East Standard Time",
"Asia/Istanbul": "Turkey Standard Time",
"Asia/Jakarta": "SE Asia Standard Time",
"Asia/Jayapura": "Tokyo Standard Time",
"Asia/Jerusalem": "Israel Standard Time",
"Asia/Kabul": "Afghanistan Standard Time",
"Asia/Kamchatka": "Russia Time Zone 11",
"Asia/Karachi": "Pakistan Standard Time",
"Asia/Kashgar": "Central Asia Standard Time",
"Asia/Kathmandu": "Nepal Standard Time",
"Asia/Katmandu": "Nepal Standard Time",
"Asia/Khandyga": "Yakutsk Standard Time",
"Asia/Kolkata": "India Standard Time",
"Asia/Krasnoyarsk": "North Asia Standard Time",
"Asia/Kuala_Lumpur": "Singapore Standard Time",
"Asia/Kuching": "Singapore Standard Time",
"Asia/Kuwait": "Arab Standard Time",
"Asia/Macao": "China Standard Time",
"Asia/Macau": "China Standard Time",
"Asia/Magadan": "Magadan Standard Time",
"Asia/Makassar": "Singapore Standard Time",
"Asia/Manila": "Singapore Standard Time",
"Asia/Muscat": "Arabian Standard Time",
"Asia/Nicosia": "GTB Standard Time",
"Asia/Novokuznetsk": "North Asia Standard Time",
"Asia/Novosibirsk": "N. Central Asia Standard Time",
"Asia/Omsk": "Omsk Standard Time",
"Asia/Oral": "West Asia Standard Time",
"Asia/Phnom_Penh": "SE Asia Standard Time",
"Asia/Pontianak": "SE Asia Standard Time",
"Asia/Pyongyang": "North Korea Standard Time",
"Asia/Qatar": "Arab Standard Time",
"Asia/Qostanay": "West Asia Standard Time",
"Asia/Qyzylorda": "Qyzylorda Standard Time",
"Asia/Rangoon": "Myanmar Standard Time",
"Asia/Riyadh": "Arab Standard Time",
"Asia/Saigon": "SE Asia Standard Time",
"Asia/Sakhalin": "Sakhalin Standard Time",
"Asia/Samarkand": "West Asia Standard Time",
"Asia/Seoul": "Korea Standard Time",
"Asia/Shanghai": "China Standard Time",
"Asia/Singapore": "Singapore Standard Time",
"Asia/Srednekolymsk": "Russia Time Zone 10",
"Asia/Taipei": "Taipei Standard Time",
"Asia/Tashkent": "West Asia Standard Time",
"Asia/Tbilisi": "Georgian Standard Time",
"Asia/Tehran": "Iran Standard Time",
"Asia/Tel_Aviv": "Israel Standard Time",
"Asia/Thimbu": "Bangladesh Standard Time",
"Asia/Thimphu": "Bangladesh Standard Time",
"Asia/Tokyo": "Tokyo Standard Time",
"Asia/Tomsk": "Tomsk Standard Time",
"Asia/Ujung_Pandang": "Singapore Standard Time",
"Asia/Ulaanbaatar": "Ulaanbaatar Standard Time",
"Asia/Ulan_Bator": "Ulaanbaatar Standard Time",
"Asia/Urumqi": "Central Asia Standard Time",
"Asia/Ust-Nera": "Vladivostok Standard Time",
"Asia/Vientiane": "SE Asia Standard Time",
"Asia/Vladivostok": "Vladivostok Standard Time",
"Asia/Yakutsk": "Yakutsk Standard Time",
"Asia/Yangon": "Myanmar Standard Time",
"Asia/Yekaterinburg": "Ekaterinburg Standard Time",
"Asia/Yerevan": "Caucasus Standard Time",
"Atlantic/Azores": "Azores Standard Time",
"Atlantic/Bermuda": "Atlantic Standard Time",
"Atlantic/Canary": "GMT Standard Time",
"Atlantic/Cape_Verde": "Cape Verde Standard Time",
"Atlantic/Faeroe": "GMT Standard Time",
"Atlantic/Faroe": "GMT Standard Time",
"Atlantic/Jan_Mayen": "W. Europe Standard Time",
"Atlantic/Madeira": "GMT Standard Time",
"Atlantic/Reykjavik": "Greenwich Standard Time",
"Atlantic/South_Georgia": "UTC-02",
"Atlantic/St_Helena": "Greenwich Standard Time",
"Atlantic/Stanley": "SA Eastern Standard Time",
"Australia/ACT": "AUS Eastern Standard Time",
"Australia/Adelaide": "Cen. Australia Standard Time",
"Australia/Brisbane": "E. Australia Standard Time",
"Australia/Broken_Hill": "Cen. Australia Standard Time",
"Australia/Canberra": "AUS Eastern Standard Time",
"Australia/Currie": "Tasmania Standard Time",
"Australia/Darwin": "AUS Central Standard Time",
"Australia/Eucla": "Aus Central W. Standard Time",
"Australia/Hobart": "Tasmania Standard Time",
"Australia/LHI": "Lord Howe Standard Time",
"Australia/Lindeman": "E. Australia Standard Time",
"Australia/Lord_Howe": "Lord Howe Standard Time",
"Australia/Melbourne": "AUS Eastern Standard Time",
"Australia/NSW": "AUS Eastern Standard Time",
"Australia/North": "AUS Central Standard Time",
"Australia/Perth": "W. Australia Standard Time",
"Australia/Queensland": "E. Australia Standard Time",
"Australia/South": "Cen. Australia Standard Time",
"Australia/Sydney": "AUS Eastern Standard Time",
"Australia/Tasmania": "Tasmania Standard Time",
"Australia/Victoria": "AUS Eastern Standard Time",
"Australia/West": "W. Australia Standard Time",
"Australia/Yancowinna": "Cen. Australia Standard Time",
"Brazil/Acre": "SA Pacific Standard Time",
"Brazil/DeNoronha": "UTC-02",
"Brazil/East": "E. South America Standard Time",
"Brazil/West": "SA Western Standard Time",
"Canada/Atlantic": "Atlantic Standard Time",
"Canada/Central": "Manitoba Standard Time",
"Canada/Eastern": "Eastern Standard Time",
"Canada/Mountain": "Alberta Standard Time",
"Canada/Newfoundland": "Newfoundland Standard Time",
"Canada/Pacific": "British Columbia Standard Time",
"Canada/Saskatchewan": "Canada Central Standard Time",
"Canada/Yukon": "Yukon Standard Time",
"Chile/Continental": "Pacific SA Standard Time",
"Chile/EasterIsland": "Easter Island Standard Time",
"Cuba": "Cuba Standard Time",
"Egypt": "Egypt Standard Time",
"Eire": "GMT Standard Time",
"Etc/GMT": "UTC",
"Etc/GMT+0": "UTC",
"Etc/GMT+1": "Cape Verde Standard Time",
"Etc/GMT+10": "Hawaiian Standard Time",
"Etc/GMT+11": "UTC-11",
"Etc/GMT+12": "Dateline Standard Time",
"Etc/GMT+2": "UTC-02",
"Etc/GMT+3": "SA Eastern Standard Time",
"Etc/GMT+4": "SA Western Standard Time",
"Etc/GMT+5": "SA Pacific Standard Time",
"Etc/GMT+6": "Central America Standard Time",
"Etc/GMT+7": "US Mountain Standard Time",
"Etc/GMT+8": "UTC-08",
"Etc/GMT+9": "UTC-09",
"Etc/GMT-0": "UTC",
"Etc/GMT-1": "W. Central Africa Standard Time",
"Etc/GMT-10": "West Pacific Standard Time",
"Etc/GMT-11": "Central Pacific Standard Time",
"Etc/GMT-12": "UTC+12",
"Etc/GMT-13": "UTC+13",
"Etc/GMT-14": "Line Islands Standard Time",
"Etc/GMT-2": "South Africa Standard Time",
"Etc/GMT-3": "E. Africa Standard Time",
"Etc/GMT-4": "Arabian Standard Time",
"Etc/GMT-5": "West Asia Standard Time",
"Etc/GMT-6": "Central Asia Standard Time",
"Etc/GMT-7": "SE Asia Standard Time",
"Etc/GMT-8": "Singapore Standard Time",
"Etc/GMT-9": "Tokyo Standard Time",
"Etc/GMT0": "UTC",
"Etc/Greenwich": "UTC",
"Etc/UCT": "UTC",
"Etc/UTC": "UTC",
"Etc/Universal": "UTC",
"Etc/Zulu": "UTC",
"Europe/Amsterdam": "W. Europe Standard Time",
"Europe/Andorra": "W. Europe Standard Time",
"Europe/Astrakhan": "Astrakhan Standard Time",
"Europe/Athens": "GTB Standard Time",
"Europe/Belfast": "GMT Standard Time",
"Europe/Belgrade": "Central Europe Standard Time",
"Europe/Berlin": "W. Europe Standard Time",
"Europe/Bratislava": "Central Europe Standard Time",
"Europe/Brussels": "Romance Standard Time",
"Europe/Bucharest": "GTB Standard Time",
"Europe/Budapest": "Central Europe Standard Time",
"Europe/Busingen": "W. Europe Standard Time",
"Europe/Chisinau": "E. Europe Standard Time",
"Europe/Copenhagen": "Romance Standard Time",
"Europe/Dublin": "GMT Standard Time",
"Europe/Gibraltar": "W. Europe Standard Time",
"Europe/Guernsey": "GMT Standard Time",
"Europe/Helsinki": "FLE Standard Time",
"Europe/Isle_of_Man": "GMT Standard Time",
"Europe/Istanbul": "Turkey Standard Time",
"Europe/Jersey": "GMT Standard Time",
"Europe/Kaliningrad": "Kaliningrad Standard Time",
"Europe/Kiev": "FLE Standard Time",
"Europe/Kirov": "Russian Standard Time",
"Europe/Kyiv": "FLE Standard Time",
"Europe/Lisbon": "GMT Standard Time",
"Europe/Ljubljana": "Central Europe Standard Time",
"Europe/London": "GMT Standard Time",
"Europe/Luxembourg": "W. Europe Standard Time",
"Europe/Madrid": "Romance Standard Time",
"Europe/Malta": "W. Europe Standard Time",
"Europe/Mariehamn": "FLE Standard Time",
"Europe/Minsk": "Belarus Standard Time",
"Europe/Monaco": "W. Europe Standard Time",
"Europe/Moscow": "Russian Standard Time",
"Europe/Nicosia": "GTB Standard Time",
"Europe/Oslo": "W. Europe Standard Time",
"Europe/Paris": "Romance Standard Time",
"Europe/Podgorica": "Central Europe Standard Time",
"Europe/Prague": "Central Europe Standard Time",
"Europe/Riga": "FLE Standard Time",
"Europe/Rome": "W. Europe Standard Time",
"Europe/Samara": "Russia Time Zone 3",
"Europe/San_Marino": "W. Europe Standard Time",
"Europe/Sarajevo": "Central European Standard Time",
"Europe/Saratov": "Saratov Standard Time",
"Europe/Simferopol": "Russian Standard Time",
"Europe/Skopje": "Central European Standard Time",
"Europe/Sofia": "FLE Standard Time",
"Europe/Stockholm": "W. Europe Standard Time",
"Europe/Tallinn": "FLE Standard Time",
"Europe/Tirane": "Central Europe Standard Time",
"Europe/Tiraspol": "E. Europe Standard Time",
"Europe/Ulyanovsk": "Astrakhan Standard Time",
"Europe/Vaduz": "W. Europe Standard Time",
"Europe/Vatican": "W. Europe Standard Time",
"Europe/Vienna": "W. Europe Standard Time",
"Europe/Vilnius": "FLE Standard Time",
"Europe/Volgograd": "Volgograd Standard Time",
"Europe/Warsaw": "Central European Standard Time",
"Europe/Zagreb": "Central European Standard Time",
"Europe/Zurich": "W. Europe Standard Time",
"GB": "GMT Standard Time",
"GB-Eire": "GMT Standard Time",
"GMT": "UTC",
"GMT+0": "UTC",
"GMT-0": "UTC",
"GMT0": "UTC",
"Greenwich": "UTC",
"Hongkong": "China Standard Time",
"Iceland": "Greenwich Standard Time",
"Indian/Antananarivo": "E. Africa Standard Time",
"Indian/Chagos": "Central Asia Standard Time",
"Indian/Christmas": "SE Asia Standard Time",
"Indian/Cocos": "Myanmar Standard Time",
"Indian/Comoro": "E. Africa Standard Time",
"Indian/Kerguelen": "West Asia Standard Time",
"Indian/Mahe": "Mauritius Standard Time",
"Indian/Maldives": "West Asia Standard Time",
"Indian/Mauritius": "Mauritius Standard Time",
"Indian/Mayotte": "E. Africa Standard Time",
"Indian/Reunion": "Mauritius Standard Time",
"Iran": "Iran Standard Time",
"Israel": "Israel Standard Time",
"Jamaica": "SA Pacific Standard Time",
"Japan": "Tokyo Standard Time",
"Kwajalein": "UTC+12",
"Libya": "Libya Standard Time",
"Mexico/BajaNorte": "Pacific Standard Time (Mexico)",
"Mexico/BajaSur": "Mountain Standard Time (Mexico)",
"Mexico/General": "Central Standard Time (Mexico)",
"NZ": "New Zealand Standard Time",
"NZ-CHAT": "Chatham Islands Standard Time",
"Navajo": "Mountain Standard Time",
"PRC": "China Standard Time",
"Pacific/Apia": "Samoa Standard Time",
"Pacific/Auckland": "New Zealand Standard Time",
"Pacific/Bougainville": "Bougainville Standard Time",
"Pacific/Chatham": "Chatham Islands Standard Time",
"Pacific/Chuuk": "West Pacific Standard Time",
"Pacific/Easter": "Easter Island Standard Time",
"Pacific/Efate": "Central Pacific Standard Time",
"Pacific/Enderbury": "UTC+13",
"Pacific/Fakaofo": "UTC+13",
"Pacific/Fiji": "Fiji Standard Time",
"Pacific/Funafuti": "UTC+12",
"Pacific/Galapagos": "Central America Standard Time",
"Pacific/Gambier": "UTC-09",
"Pacific/Guadalcanal": "Central Pacific Standard Time",
"Pacific/Guam": "West Pacific Standard Time",
"Pacific/Honolulu": "Hawaiian Standard Time",
"Pacific/Johnston": "Hawaiian Standard Time",
"Pacific/Kanton": "UTC+13",
"Pacific/Kiritimati": "Line Islands Standard Time",
"Pacific/Kosrae": "Central Pacific Standard Time",
"Pacific/Kwajalein": "UTC+12",
"Pacific/Majuro": "UTC+12",
"Pacific/Marquesas": "Marquesas Standard Time",
"Pacific/Midway": "UTC-11",
"Pacific/Nauru": "UTC+12",
"Pacific/Niue": "UTC-11",
"Pacific/Norfolk": "Norfolk Standard Time",
"Pacific/Noumea": "Central Pacific Standard Time",
"Pacific/Pago_Pago": "UTC-11",
"Pacific/Palau": "Tokyo Standard Time",
"Pacific/Pitcairn": "UTC-08",
"Pacific/Pohnpei": "Central Pacific Standard Time",
"Pacific/Ponape": "Central Pacific Standard Time",
"Pacific/Port_Moresby": "West Pacific Standard Time",
"Pacific/Rarotonga": "Hawaiian Standard Time",
"Pacific/Saipan": "West Pacific Standard Time",
"Pacific/Samoa": "UTC-11",
"Pacific/Tahiti": "Hawaiian Standard Time",
"Pacific/Tarawa": "UTC+12",
"Pacific/Tongatapu": "Tonga Standard Time",
"Pacific/Truk": "West Pacific Standard Time",
"Pacific/Wake": "UTC+12",
"Pacific/Wallis": "UTC+12",
"Poland": "Central European Standard Time",
"Portugal": "GMT Standard Time",
"ROC": "Taipei Standard Time",
"ROK": "Korea Standard Time",
"Singapore": "Singapore Standard Time",
"Turkey": "Turkey Standard Time",
"UCT": "UTC",
"US/Alaska": "Alaskan Standard Time",
"US/Aleutian": "Aleutian Standard Time",
"US/Arizona": "US Mountain Standard Time",
"US/Central": "Central Standard Time",
"US/Eastern": "Eastern Standard Time",
"US/Hawaii": "Hawaiian Standard Time",
"US/Indiana-Starke": "Central Standard Time",
"US/Michigan": "Eastern Standard Time",
"US/Mountain": "Mountain Standard Time",
"US/Pacific": "Pacific Standard Time",
"US/Samoa": "UTC-11",
"UTC": "UTC",
"Universal": "UTC",
"W-SU": "Russian Standard Time",
"Zulu": "UTC",
}
+85
View File
@@ -0,0 +1,85 @@
"""The event channels as the host's log sources (NetOrk/netork#2897).
:class:`WindowsLogSourcesMixin` gives the driver ``get_log_sources`` in napalm-device-types'
shape (``LogSourcesDict``). A Windows host keeps no journal and its programs hold no log
files a reader could name: its logs are its event channels, each a source of kind
``eventlog`` named by its channel -- the name CrowdSec (``event_channel``) and Wazuh
(``eventchannel``) read it by -- with its ``.evtx`` file as ``path``.
One script, ``Get-WinEvent -ListLog *``: every channel that is switched on and holds
records, with its file (``%SystemRoot%`` expanded), size, last write and type. A channel
the account may not open is skipped, not the reading. Analytic and debug channels are
trace sessions written to ``.etl`` files, which a log reader cannot follow, and are left
out. WinRM needs an administrator, who may open every other channel, the Security log
included, so the reading is ``attributed``. Where the logs go beyond the host (Windows
Event Forwarding, an agent) is not read: ``forwarding`` is None.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types import LogSourceDict, LogSourcesDict, eventlog_source
from napalm_windows._powershell import _as_list
_PS_EVENT_CHANNELS = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-WinEvent -ListLog * -ErrorAction SilentlyContinue |
Where-Object { $_.IsEnabled -and $_.RecordCount } |
ForEach-Object {
[pscustomobject]@{
channel = $_.LogName
path = [Environment]::ExpandEnvironmentVariables([string]$_.LogFilePath)
size = $_.FileSize
modified = if ($_.LastWriteTime) {
([DateTimeOffset]$_.LastWriteTime).ToUnixTimeSeconds()
} else { $null }
records = $_.RecordCount
type = [string]$_.LogType
}
}
)
"""
#: Trace sessions, not logs: written to .etl files a reader cannot follow.
_TRACE_TYPES = frozenset({"analytic", "debug"})
def _is_log(raw: dict[str, Any]) -> bool:
return (
bool(raw.get("channel"))
and int(raw.get("records") or 0) > 0
and str(raw.get("type") or "").lower() not in _TRACE_TYPES
)
def _source(raw: dict[str, Any]) -> LogSourceDict:
size, modified = raw.get("size"), raw.get("modified")
return eventlog_source(
str(raw["channel"]),
str(raw["path"]) if raw.get("path") else None,
None if size is None else int(size),
None if modified is None else float(modified),
)
class WindowsLogSourcesMixin:
"""``get_log_sources``: the host's event channels; 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_log_sources(self) -> LogSourcesDict:
"""Every event channel that is switched on and holds records, sorted by name.
* attributed (bool) - always True: an administrator opens every channel
* journald (bool) - always False: Windows keeps event channels, not a journal
* sources (list) - one ``eventlog`` source per channel
* forwarding - None: where the logs go beyond the host is not read
"""
channels = [c for c in _as_list(self._run_ps(_PS_EVENT_CHANNELS)) if _is_log(c)]
sources = sorted((_source(c) for c in channels), key=lambda s: s.get("channel", ""))
return {"attributed": True, "journald": False, "sources": sources, "forwarding": None}
+28
View File
@@ -0,0 +1,28 @@
"""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."""
+254
View File
@@ -0,0 +1,254 @@
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
:class:`WindowsHostEventsMixin` implements napalm-device-types'
:class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries
the script across ``PsrpTransport.run``.
**One script, three queries**, each an XPath filter over a fixed set of providers and
event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and
bounded by count:
* *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008
(an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss),
WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a
fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption);
* *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger
19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control
Manager 7031 and 7034 (a service that ended unexpectedly);
* *apps*, the Application log without messages: Application Error 1000 (a program that
crashed, its path the eleventh property).
``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under
``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query
catches it as no events. Any other failure costs only that query, whose kinds the
reading names ``unread``; a query that returned its bound names its kinds ``capped``.
**What an event is about** is taken from its properties, which do not depend on the
host's language, never from its message, which does: the stop code, the disk or volume,
the program's path (its name on a Windows that records no path), the service's display
name. The message is kept as the host wrote it, cut short.
"""
from __future__ import annotations
import time
from collections.abc import Callable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin
from napalm_device_types import host_event as _event
from napalm_device_types.host_events import (
APP_CRASH,
DISK_ERROR,
HARDWARE_ERROR_CORRECTED,
HARDWARE_ERROR_FATAL,
HOST_EVENT_MESSAGE_CHARS,
HOST_EVENT_WINDOW_DAYS,
SERVICE_CRASH,
SYSTEM_CRASH,
UNEXPECTED_SHUTDOWN,
)
from napalm_windows._powershell import _as_list
_KERNEL_POWER = "Microsoft-Windows-Kernel-Power"
_BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting"
_WHEA = "Microsoft-Windows-WHEA-Logger"
_SCM = "Service Control Manager"
_APP_ERROR = "Application Error"
def _bugcheck(props: list[str]) -> str | None:
"""Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none."""
word = props[0].strip() if props else ""
return f"0x{int(word):08x}" if word.isdigit() and int(word) else None
def _stop_code(props: list[str]) -> str | None:
"""1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``."""
word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else ""
return word or None
def _first(props: list[str]) -> str | None:
return props[0] if props else None
def _program(props: list[str]) -> str | None:
"""Application Error 1000: its path where the host records one, else its name."""
path = props[10] if len(props) > 10 else ""
return path.strip() or _first(props)
def _none(props: list[str]) -> str | None:
return None
_Subject = Callable[[list[str]], str | None]
#: (provider, event ID) -> the kind and what the event is about.
_EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = {
(_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck),
("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none),
(_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code),
(_WHEA, 18): (HARDWARE_ERROR_FATAL, _none),
(_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none),
(_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none),
("disk", 7): (DISK_ERROR, _first),
("disk", 153): (DISK_ERROR, _first),
("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first),
("Ntfs", 55): (DISK_ERROR, _first),
(_SCM, 7031): (SERVICE_CRASH, _first),
(_SCM, 7034): (SERVICE_CRASH, _first),
(_APP_ERROR, 1000): (APP_CRASH, _program),
}
#: Each query's log, its events, its bound and whether it reads their messages.
_QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = {
"rare": (
"System",
(
(_KERNEL_POWER, 41),
("EventLog", 6008),
(_BUGCHECK, 1001),
(_WHEA, 18),
("disk", 7),
("Microsoft-Windows-Ntfs", 55),
("Ntfs", 55),
),
100,
True,
),
"frequent": (
"System",
((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)),
500,
False,
),
"apps": ("Application", ((_APP_ERROR, 1000),), 200, False),
}
#: The kinds each query reads, in the order of HOST_EVENT_KINDS.
_PART_KINDS: dict[str, tuple[str, ...]] = {
part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events})
for part, (_log, events, _max, _message) in _QUERIES.items()
}
# Q runs one query: its events with their properties as strings, or why not.
# $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure.
_PS_QUERY = rf"""
$ErrorActionPreference = 'Stop'
function Q($log, $xpath, $max, $withMessage) {{
try {{
$rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{
$m = $null
if ($withMessage) {{
try {{ $m = [string]$_.Message }} catch {{ $m = $null }}
if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{
$m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS})
}}
}}
[pscustomobject]@{{
provider = $_.ProviderName
id = [int]$_.Id
time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds()
props = @($_.Properties | Select-Object -First 11 |
ForEach-Object {{ [string]$_.Value }})
message = $m
}}
}})
[pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }}
}} catch {{
if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{
[pscustomobject]@{{ ok = $true; capped = $false; events = @() }}
}} else {{
[pscustomobject]@{{
ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message
}}
}}
}}
}}
"""
def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str:
which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events)
return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]"
def host_events_script(since: float) -> str:
"""The reading's script, from *since* (unix seconds) on."""
start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
lines = [_PS_QUERY]
parts = []
for part, (log, events, bound, message) in _QUERIES.items():
lines.append(f'${part} = "{_xpath(events, start)}"')
parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})")
lines.append("[pscustomobject]@{ parts = [pscustomobject]@{")
lines.extend(parts)
lines.append("} } | ConvertTo-Json -Compress -Depth 6")
return "\n".join(lines) + "\n"
def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None:
known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0)))
if known is None:
return None
kind, subject = known
props = [str(p) for p in _as_list(raw.get("props"))]
source = f"{source_log}: {raw.get('provider')} {raw.get('id')}"
return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message"))
def _part(answer: Any, log: str) -> list[HostEventDict] | None:
"""One query's events; None when it was not read."""
if not isinstance(answer, dict) or not answer.get("ok"):
return None
found = (_parse_event(e, log) for e in _as_list(answer.get("events")))
return [e for e in found if e is not None]
def _in_order(kinds: set[str]) -> list[str]:
return [k for k in HOST_EVENT_KINDS if k in kinds]
def _reading(raw: Any, since: float) -> HostEventsDict:
if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict):
raise ValueError("the host events reading came back without a report")
events: list[HostEventDict] = []
capped: set[str] = set()
unread: set[str] = set()
for part, (log, _events, _bound, _message) in _QUERIES.items():
answer = raw["parts"].get(part)
found = _part(answer, log)
if found is None:
unread.update(_PART_KINDS[part])
continue
if answer.get("capped"):
capped.update(_PART_KINDS[part])
events.extend(found)
events.sort(key=lambda e: e["time"], reverse=True)
return {
"since": datetime.fromtimestamp(since, UTC).isoformat(),
"events": events,
"capped": _in_order(capped),
"unread": _in_order(unread),
}
class WindowsHostEventsMixin(HostEventsMixin):
"""The event log's warnings-worthy events; 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_host_events(self, since: float | None = None) -> HostEventsDict:
"""The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default
over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module.
:raises ValueError: when the reading came back without a report.
"""
start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since
return _reading(self._run_ps(host_events_script(start)), start)
+357
View File
@@ -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)
+230
View File
@@ -0,0 +1,230 @@
"""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"))
+424
View File
@@ -0,0 +1,424 @@
"""Who can log in to a Windows host, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginAccountsMixin` fills napalm-device-types' ``get_login_accounts``
reading (``LoginAccountsDict``) from one script, read-only:
- **The accounts** are the host's own, ``Get-LocalUser`` (probed with ``Get-Command``
first: without it the reading is not supported). ``DefaultAccount`` and
``WDAGUtilityAccount`` (RIDs 503 and 504) are the system's and are left out, as Linux
leaves out its system accounts. ``uid`` is the RID, the SID's last part, and ``sid``
the whole SID. ``home`` is the profile's folder (``Win32_UserProfile``); Windows has no
login shell, so ``shell`` is empty.
- **The last login** is the account database's (``LastLogon``), source ``sam``; it knows
no address or terminal.
- **Lock and expiry:** an account is ``locked`` when it is disabled, expired or locked out
(``IsAccountLocked`` of the ``WinNT:`` provider); the password's last change and expiry
are ``Get-LocalUser``'s. A password that never expires has no ``PasswordExpires``.
- **The failed attempts since the last login** are ``BadPasswordAttempts`` (``WinNT:``),
which a successful login resets, source ``sam``.
- **Administrators and Remote Desktop** go by SID, never by name: the Administrators
group is ``S-1-5-32-544`` in every language ("Administratoren"). Its members, and those
of every local group that holds or is denied the right to log in through Remote Desktop
Services (``SeRemoteInteractiveLogonRight``, ``SeDenyRemoteInteractiveLogonRight``, from
``secedit /export``), are read through ``WinNT:``, a domain's groups and accounts by
name. An account may log in at a remote desktop when the host takes such logins
(``fDenyTSConnections``, group policy's first), one of its SIDs holds the right and
none is denied it. Its SIDs are its own, those every local account's logon carries
(Everyone, Authenticated Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account)
and the local groups it or one of those is a member of.
- **A domain controller** has no accounts of its own: they are the directory's, reviewed
there. Its accounts are not read; its groups are.
Each part that fails leaves its fields ``None`` (not read), never "no"; the script's
``errors`` say which.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_accounts import (
LoginAccountDict,
LoginAccountsDict,
LoginGroupDict,
LoginGroupMemberDict,
)
logger = logging.getLogger(__name__)
#: The account database: where the last logins and the failed attempts come from.
SOURCE = "sam"
ADMINISTRATORS = "S-1-5-32-544"
REMOTE_DESKTOP_USERS = "S-1-5-32-555"
#: The system's own accounts: DefaultAccount, WDAGUtilityAccount.
_SYSTEM_RIDS = frozenset({503, 504})
#: Win32_ComputerSystem.DomainRole of a backup and a primary domain controller.
_DOMAIN_CONTROLLER = 4
#: The SIDs every local account's remote desktop logon carries: Everyone, Authenticated
#: Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account.
_LOGON_SIDS = frozenset({"S-1-1-0", "S-1-5-11", "S-1-5-4", "S-1-5-14", "S-1-5-113"})
#: Local account and member of the Administrators group.
_LOCAL_ADMIN = "S-1-5-114"
#: The SIDs of a domain's or the host's own accounts and groups, and of Entra ID's; any
#: other SID is a principal of the host itself (Everyone, INTERACTIVE, the BUILTIN groups).
_ACCOUNT_SIDS = ("S-1-5-21-", "S-1-12-")
_PS_LOGIN_ACCOUNTS = r"""
$ErrorActionPreference = 'Stop'
$errors = @()
$tsKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
$tsPolicy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
$rdpRight = 'SeRemoteInteractiveLogonRight'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function V($path, $name) {
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
if ($item) { [string]$item.$name }
}
function Prop($o, $name) { $o.GetType().InvokeMember($name, 'GetProperty', $null, $o, $null) }
function Sid($value) { New-Object Security.Principal.SecurityIdentifier $value }
function UserFlag($name, $prop) {
try {
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',user')
$entry.psbase.InvokeGet($prop)
} catch { $null }
}
function GroupMember($m) {
$bytes = $null
try { $bytes = [byte[]](Prop $m 'objectSid') } catch { }
$sid = $null
if ($bytes) { $sid = [Security.Principal.SecurityIdentifier]::new($bytes, 0).Value }
[pscustomobject]@{
path = [string](Prop $m 'ADsPath')
class = [string](Prop $m 'Class')
sid = $sid
}
}
function LocalGroup($sid) {
$account = (Sid $sid).Translate([Security.Principal.NTAccount]).Value
$domain, $name = $account.Split('\', 2)
if ($null -eq $name) { return }
if ($domain -ne 'BUILTIN' -and $domain -ne $env:COMPUTERNAME) { return }
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',group')
[pscustomobject]@{
sid = $sid
name = $name
members = @($entry.psbase.Invoke('Members') | ForEach-Object { GroupMember $_ })
}
}
function Holders($text) { @($text.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
function Rights {
$file = 'Temp\napalm-windows-' + [guid]::NewGuid().ToString('N') + '.inf'
$cfg = Join-Path $env:SystemRoot $file
try {
$null = cmd.exe /c ('secedit /export /areas USER_RIGHTS /cfg ' + $cfg + ' 2>&1')
if (-not (Test-Path -LiteralPath $cfg)) { return }
$allow = @(); $deny = @()
foreach ($line in Get-Content -LiteralPath $cfg) {
if ($line -match '^\s*(Se\w+)\s*=\s*(.*)$') {
if ($Matches[1] -eq $rdpRight) { $allow = Holders $Matches[2] }
if ($Matches[1] -eq ('SeDeny' + $rdpRight)) { $deny = Holders $Matches[2] }
}
}
[pscustomobject]@{ allow = $allow; deny = $deny }
} finally { Remove-Item -LiteralPath $cfg -ErrorAction SilentlyContinue }
}
$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
$homes = @{}
try {
Get-CimInstance -ClassName Win32_UserProfile |
ForEach-Object { $homes[[string]$_.SID] = [string]$_.LocalPath }
} catch { $errors += 'profiles: ' + $_ }
$users = $null
if ($role -ge 4) { $users = @() }
elseif (Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue) {
$users = @(Get-LocalUser | ForEach-Object {
$sid = [string]$_.SID.Value
[pscustomobject]@{
name = $_.Name
sid = $sid
enabled = [bool]$_.Enabled
home = $homes[$sid]
last_logon = Ms $_.LastLogon
password_last_set = Ms $_.PasswordLastSet
password_expires = Ms $_.PasswordExpires
account_expires = Ms $_.AccountExpires
bad_passwords = UserFlag $_.Name 'BadPasswordAttempts'
locked_out = UserFlag $_.Name 'IsAccountLocked'
}
})
}
$rights = $null
try { $rights = Rights } catch { $errors += 'rights: ' + $_ }
$wanted = @('S-1-5-32-544', 'S-1-5-32-555')
if ($rights) {
$wanted += @(@($rights.allow) + @($rights.deny) | Where-Object { $_.StartsWith('*') } |
ForEach-Object { $_.Substring(1) })
}
$groups = @(foreach ($sid in @($wanted | Select-Object -Unique)) {
try { LocalGroup $sid } catch { $errors += 'group ' + $sid + ': ' + $_ }
})
[pscustomobject]@{
computer = $env:COMPUTERNAME
domain_role = $role
admin = [bool]$me.IsInRole((Sid 'S-1-5-32-544'))
now = Ms (Get-Date)
users = $users
groups = $groups
rights = $rights
rdp_deny = V $tsKey 'fDenyTSConnections'
rdp_deny_policy = V $tsPolicy 'fDenyTSConnections'
errors = $errors
} | ConvertTo-Json -Compress -Depth 6
"""
def _iso(ms: Any) -> str | None:
"""Milliseconds since the epoch as ISO 8601 in UTC; None for none."""
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _date(ms: Any) -> str | None:
iso = _iso(ms)
return None if iso is None else iso[:10]
def _rid(sid: str) -> int | None:
try:
return int(sid.rsplit("-", 1)[1])
except (IndexError, ValueError):
return None
def _local(sid: str | None, domain: str | None, computer: str, machine: str | None) -> bool | None:
"""Whether a member is the host's own: by its SID where it says, else by its path."""
if sid and not sid.upper().startswith(_ACCOUNT_SIDS):
return True
if sid and machine:
return sid.rsplit("-", 1)[0].upper() == machine
return None if domain is None else domain.upper() == computer.upper()
def _member_name(parts: list[str], sid: str | None) -> tuple[str, str | None]:
"""The member's name as ``DOMAIN\\name`` and its domain; a bare SID has none."""
if len(parts) >= 2:
return f"{parts[-2]}\\{parts[-1]}", parts[-2]
return (parts[0] if parts else str(sid or "")), None
def _is_group(raw: dict[str, Any]) -> bool | None:
kind = str(raw.get("class") or "").lower()
return {"group": True, "user": False}.get(kind)
def _member(raw: dict[str, Any], computer: str, machine: str | None) -> LoginGroupMemberDict:
"""A ``WinNT:`` member: ``WinNT://DOMAIN/name``, ``WinNT://WORKGROUP/HOST/name`` for
the host's own, ``WinNT://S-1-5-…`` for a SID the host can no longer resolve."""
parts = [p for p in str(raw.get("path") or "").removeprefix("WinNT://").split("/") if p]
sid = str(raw.get("sid") or "") or None
name, domain = _member_name(parts, sid)
return {
"name": name,
"sid": sid,
"local": _local(sid, domain, computer, machine),
"group": _is_group(raw),
}
class _Rights:
"""Who holds and who is denied a remote desktop login; None where not read."""
def __init__(self, raw: dict[str, Any]) -> None:
rights = raw.get("rights")
self.read = isinstance(rights, dict)
holders = rights if isinstance(rights, dict) else {}
self.allow = {h.lstrip("*").upper() for h in _as_list(holders.get("allow"))}
self.deny = {h.lstrip("*").upper() for h in _as_list(holders.get("deny"))}
value = raw.get("rdp_deny_policy")
value = raw.get("rdp_deny") if value in (None, "") else value
self.enabled: bool | None = None if value in (None, "") else str(value).strip() == "0"
def holds(self, names: set[str]) -> bool | None:
"""Whether one of *names* (SIDs, account names) may log in at a remote desktop."""
if self.enabled is False:
return False
if self.enabled is None or not self.read:
return None
names = {n.upper() for n in names}
return bool(names & self.allow) and not names & self.deny
class _Groups:
"""The local groups read, by SID, with their members' SIDs."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = [g for g in _as_list(raw.get("groups")) if isinstance(g, dict) and g.get("sid")]
self.members = {
str(g["sid"]).upper(): {
str(m.get("sid")).upper() for m in _as_list(g.get("members")) if m.get("sid")
}
for g in self.raw
}
def of(self, sid: str) -> set[str]:
"""The SIDs a local account's remote desktop logon carries."""
own = {sid.upper(), *_LOGON_SIDS}
groups = {g for g, members in self.members.items() if members & own}
extra = {_LOCAL_ADMIN} if ADMINISTRATORS in groups else set()
return own | groups | extra
def administrator(self, sid: str) -> bool | None:
if ADMINISTRATORS not in self.members:
return None
return ADMINISTRATORS in self.of(sid)
def _locked(user: dict[str, Any], now: Any) -> bool | None:
expires = user.get("account_expires")
if user.get("enabled") is False:
return True
if isinstance(expires, int | float) and isinstance(now, int | float) and expires <= now:
return True
locked_out = user.get("locked_out")
return locked_out if isinstance(locked_out, bool) else None
def _failed(user: dict[str, Any]) -> int | None:
value = user.get("bad_passwords")
return value if isinstance(value, int) and not isinstance(value, bool) else None
def _password_expires(user: dict[str, Any]) -> str | None:
"""The date, or "never" for a password set that never expires; None when not set."""
expires = _date(user.get("password_expires"))
if expires is not None:
return expires
return "never" if user.get("password_last_set") is not None else None
def _account(
user: dict[str, Any], rid: int, raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> LoginAccountDict:
sid = str(user["sid"])
last = _iso(user.get("last_logon"))
changed = _date(user.get("password_last_set"))
return {
"name": str(user.get("name") or ""),
"uid": rid,
"home": str(user.get("home") or ""),
"shell": "",
"last_login": last,
"last_login_from": None,
"last_login_port": None,
"last_login_source": SOURCE if last else None,
"password": "set" if changed else None,
"password_changed": changed,
"password_expires": _password_expires(user),
"account_expires": _date(user.get("account_expires")) or "never",
"locked": _locked(user, raw.get("now")),
"failed_logins": _failed(user),
"failed_logins_capped": False,
"sid": sid,
"administrator": groups.administrator(sid),
"remote_desktop": rights.holds(groups.of(sid) | {str(user.get("name") or "")}),
}
def _accounts(
users: Iterable[Any], raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> list[LoginAccountDict]:
accounts = []
for user in users:
rid = _rid(str(user.get("sid") or "")) if isinstance(user, dict) else None
if rid is not None and rid not in _SYSTEM_RIDS:
accounts.append(_account(user, rid, raw, groups, rights))
return accounts
def _grants(sid: str, rights: _Rights) -> list[str]:
grants = ["administrator"] if sid.upper() == ADMINISTRATORS else []
if rights.holds({sid}):
grants.append("remote_desktop")
return grants
def _machine(users: Iterable[Any]) -> str | None:
"""The host's own SID, its accounts' SIDs without the RID; None without accounts."""
for user in users:
sid = str(user.get("sid") or "") if isinstance(user, dict) else ""
if sid.upper().startswith("S-1-5-21-"):
return sid.rsplit("-", 1)[0].upper()
return None
def _login_groups(raw: dict[str, Any], groups: _Groups, rights: _Rights) -> list[LoginGroupDict]:
computer = str(raw.get("computer") or "")
machine = _machine(_as_list(raw.get("users")))
found: list[LoginGroupDict] = []
for group in groups.raw:
grants = _grants(str(group["sid"]), rights)
if grants:
found.append(
{
"name": str(group.get("name") or ""),
"sid": str(group["sid"]),
"grants": grants,
"members": [
_member(m, computer, machine) for m in _as_list(group.get("members"))
],
}
)
return found
def parse_login_accounts(raw: dict[str, Any]) -> LoginAccountsDict:
"""What :data:`_PS_LOGIN_ACCOUNTS` emitted, as napalm-device-types' reading.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
"""
for error in _as_list(raw.get("errors")):
logger.info("login accounts: part not read: %s", error)
users = raw.get("users")
if users is None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER:
raise NotImplementedError("Get-LocalUser is not available on this host")
groups, rights = _Groups(raw), _Rights(raw)
accounts = _accounts(_as_list(users), raw, groups, rights)
read = users is not None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER
failures = any(a["failed_logins"] is not None for a in accounts)
return {
"accounts": accounts,
"login_sources": [SOURCE] if read else [],
"failed_logins_source": SOURCE if failures else None,
"privileged": raw.get("admin") is True,
"groups": _login_groups(raw, groups, rights),
}
class WindowsLoginAccountsMixin:
"""``get_login_accounts`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_accounts(self) -> LoginAccountsDict:
"""Every account of the host and who can administer it or log in at a remote
desktop, in napalm-device-types' ``LoginAccountsDict``; see the module.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_ACCOUNTS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login account reading came back empty")
return parse_login_accounts(raw)
+265
View File
@@ -0,0 +1,265 @@
"""The logins a Windows host recorded, at its console and over Remote Desktop
(NetOrk/netork#2895).
:class:`WindowsLoginSessionsMixin` fills napalm-device-types' ``get_login_sessions``
reading (``LoginSessionsDict``) from the Security event log, in one script, read-only:
- **The logons** are event 4624 of the last :data:`SESSION_WINDOW_DAYS` days, bounded on
the host (``timediff``), the newest :data:`SESSIONS_READ`: logon type 2 (at the
console), 10 (Remote Desktop) and 11 (at the console with cached credentials), as
``tty`` ``console`` or ``rdp``. Not type 3 (network): every SMB access and every WinRM
connection is one, this reading's own included; nor 7, an unlock of a session already
read. Only a person's account counts -- a SID of the host, a domain (``S-1-5-21-``) or
Entra ID (``S-1-12-``) -- not the window manager's or the font driver's (``DWM-1``,
``UMFD-0``). An administrator's logon is two events, a full and a filtered token
linked to each other (``TargetLinkedLogonId``): one session.
- **The end** is the logoff of the logon (4634, or 4647 when the user logged off). The
account is ``DOMAIN\\name``, the host's own accounts by name alone. The address is the
event's ``IpAddress``; a console logon's loopback is none.
- **The reading's own address** is that of its own WinRM logon: the session's logon ID
(``Win32_SessionProcess``, else the logon SID ``S-1-5-5-X-Y`` of its token) names its
4624 event. Where that event has no address, the one client connected to WinRM's ports
(``Get-NetTCPConnection``); several, none. Remote Desktop sessions from it are left out,
as on Linux the reading's own SSH sessions are.
- **Coverage:** the Security log rotates by size, often within days. ``records_since`` is
its oldest event, so a login before it is unknown rather than absent. A host that holds
not even this reading's own logon and no other in the window does not audit logons:
:class:`LoginSessionsUnavailable`, never "nobody logged in".
``Get-WinEvent`` answers no match with an error (``NoMatchingEventsFound``); the script
takes that for none. Reading the Security log takes an administrator.
"""
from __future__ import annotations
import ipaddress
import json
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types.login_sessions import (
SESSION_WINDOW_DAYS,
SESSIONS_READ,
LoginSessionsUnavailable,
session_address,
)
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_sessions import LoginSessionDict, LoginSessionsDict
#: Logon type → terminal: at the console, Remote Desktop, at the console with cached
#: credentials.
LOGON_TYPES = {"2": "console", "10": "rdp", "11": "console"}
#: The SIDs of a person's account: the host's or a domain's, and Entra ID's.
_PERSON_SIDS = ("S-1-5-21-", "S-1-12-")
_DAY_MS = 86_400_000
_PS_SESSIONS_TEMPLATE = r"""
$ErrorActionPreference = 'Stop'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function Events($filter, $max, [switch]$Oldest) {
try { Get-WinEvent -LogName Security -FilterXPath $filter -MaxEvents $max -Oldest:$Oldest }
catch { if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } }
}
function P($e, $i) { if ($e.Properties.Count -gt $i) { [string]$e.Properties[$i].Value } }
function Logon($t) { "Data[@Name='LogonType']='" + $t + "'" }
function Query($id, $data) {
$within = 'TimeCreated[timediff(@SystemTime) <= __WINDOW_MS__]'
$system = "*[System[EventID=" + $id + " and " + $within + "]"
if ($data) { $system + " and EventData[" + $data + "]]" } else { $system + "]" }
}
$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)
$ownId = $null
try {
$query = "ASSOCIATORS OF {Win32_Process.Handle='" + $PID + "'}" +
" WHERE AssocClass=Win32_SessionProcess"
$session = @(Get-CimInstance -Query $query)
if ($session.Count -gt 0) { $ownId = [uint64]$session[0].LogonId }
} catch { }
if ($null -eq $ownId) {
$groups = [Security.Principal.WindowsIdentity]::GetCurrent().Groups
$logonSid = @($groups | Where-Object { $_.Value -like 'S-1-5-5-*' })
if ($logonSid.Count -gt 0) {
$parts = $logonSid[0].Value.Split('-')
$ownId = ([uint64]$parts[4] -shl 32) + [uint64]$parts[5]
}
}
$canary = $null; $ownIp = $null
if ($null -ne $ownId) {
$mine = "Data[@Name='TargetLogonId']='" + ('0x{0:x}' -f $ownId) + "'"
$within = 'TimeCreated[timediff(@SystemTime) <= __DAY_MS__]'
$own = @(Events ("*[System[EventID=4624 and " + $within + "] and EventData[" + $mine + "]]") 1)
$canary = $own.Count -gt 0
if ($canary) { $ownIp = P $own[0] 18 }
}
$peers = @()
try {
$winrm = Get-NetTCPConnection -State Established -LocalPort 5985, 5986 `
-ErrorAction SilentlyContinue
$peers = @($winrm | ForEach-Object { [string]$_.RemoteAddress } | Sort-Object -Unique)
} catch { }
$logons = @(Events (Query 4624 $types) __READ__ | ForEach-Object {
[pscustomobject]@{
t = Ms $_.TimeCreated; sid = P $_ 4; user = P $_ 5; domain = P $_ 6
id = P $_ 7; type = P $_ 8; ip = P $_ 18; linked = P $_ 25
}
})
$ended = @(Events (Query 4634 $types) __ENDS__) + @(Events (Query 4647 $null) __READ__)
$ends = @($ended | ForEach-Object { [pscustomobject]@{ t = Ms $_.TimeCreated; id = P $_ 3 } })
$first = @(Events '*' 1 -Oldest)
[pscustomobject]@{
computer = $env:COMPUTERNAME
canary = $canary
own_ip = $ownIp
winrm_peers = $peers
oldest = if ($first.Count -gt 0) { Ms $first[0].TimeCreated } else { $null }
logons = $logons
ends = $ends
} | ConvertTo-Json -Compress -Depth 4
"""
#: The script: the window, a day for its own logon, and the events read, filled in.
_PS_LOGIN_SESSIONS = (
_PS_SESSIONS_TEMPLATE.replace("__WINDOW_MS__", str(SESSION_WINDOW_DAYS * _DAY_MS))
.replace("__DAY_MS__", str(_DAY_MS))
.replace("__READ__", str(SESSIONS_READ))
.replace("__ENDS__", str(2 * SESSIONS_READ))
)
def _iso(ms: Any) -> str | None:
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _id(value: Any) -> int | None:
"""A logon ID as the event gives it, decimal; None for none or 0 (no linked logon)."""
try:
number = int(str(value))
except ValueError:
return None
return number or None
def _own_address(raw: dict[str, Any]) -> str | None:
"""Where this reading's own WinRM logon came from: its 4624 event's address, else the
one client connected to WinRM."""
own = session_address(raw.get("own_ip")) if raw.get("canary") else None
if own is not None:
return own
peers = {session_address(str(p)) for p in _as_list(raw.get("winrm_peers"))} - {None}
return peers.pop() if len(peers) == 1 else None
def _user(event: dict[str, Any], computer: str) -> str:
user, domain = str(event.get("user") or ""), str(event.get("domain") or "")
return user if not domain or domain.upper() == computer.upper() else f"{domain}\\{user}"
def _address(event: dict[str, Any], tty: str) -> str | None:
address = session_address(event.get("ip"))
if tty == "console" and address is not None:
try:
if ipaddress.ip_address(address).is_loopback:
return None
except ValueError:
return address
return address
def _ends(raw: dict[str, Any]) -> dict[int, list[int]]:
"""Each logon ID's logoffs, in milliseconds: an ID is used again after a restart."""
ends: dict[int, list[int]] = {}
for end in _as_list(raw.get("ends")):
logon, at = _id(end.get("id")), end.get("t")
if logon is not None and isinstance(at, int):
ends.setdefault(logon, []).append(at)
return ends
def _logons(events: list[dict[str, Any]]) -> Iterable[dict[str, Any]]:
"""The 4624 events of a person's interactive logon, one per linked pair."""
seen: set[int] = set()
for event in sorted(events, key=lambda e: int(e["t"])):
logon, linked = _id(event.get("id")), _id(event.get("linked"))
if logon is None or str(event.get("type")) not in LOGON_TYPES:
continue
if not str(event.get("sid") or "").upper().startswith(_PERSON_SIDS):
continue
key = min(logon, linked) if linked else logon
if key not in seen:
seen.add(key)
yield event
def _session(event: dict[str, Any], computer: str, ends: dict[int, list[int]]) -> LoginSessionDict:
tty = LOGON_TYPES[str(event.get("type"))]
started = int(event["t"])
ids = [i for i in (_id(event.get("id")), _id(event.get("linked"))) if i is not None]
ended = [at for i in ids for at in ends.get(i, ()) if at >= started]
return {
"user": _user(event, computer),
"tty": tty,
"address": _address(event, tty),
"started": _iso(started) or "",
"ended": _iso(min(ended)) if ended else None,
}
def _audited_logons(raw: dict[str, Any]) -> list[dict[str, Any]]:
"""The logon events read; raises when the log holds none, not even this reading's own."""
logons = [e for e in _as_list(raw.get("logons")) if isinstance(e, dict)]
if raw.get("canary") is False and not logons:
raise LoginSessionsUnavailable(
"the Security log holds no logon, not even this reading's own: logons are not audited"
)
return [e for e in logons if isinstance(e.get("t"), int)]
def _sessions(
logons: list[dict[str, Any]], raw: dict[str, Any], own: str | None
) -> list[LoginSessionDict]:
"""The sessions newest first, those from *own* left out, at most SESSIONS_READ."""
computer, ends = str(raw.get("computer") or ""), _ends(raw)
sessions = [_session(e, computer, ends) for e in _logons(logons)]
sessions = [s for s in sessions if own is None or s["address"] != own]
sessions.sort(key=lambda s: s["started"], reverse=True)
return sessions[:SESSIONS_READ]
def parse_login_sessions(raw: dict[str, Any]) -> LoginSessionsDict:
"""What :data:`_PS_LOGIN_SESSIONS` emitted, as napalm-device-types' reading.
:raises LoginSessionsUnavailable: when the host does not audit logons.
"""
logons = _audited_logons(raw)
own = _own_address(raw)
return {
"own_address": own,
"sessions": _sessions(logons, raw, own),
"records_since": _iso(raw.get("oldest")),
}
class WindowsLoginSessionsMixin:
"""``get_login_sessions`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_sessions(self) -> LoginSessionsDict:
"""The console and Remote Desktop logins of the last seven days, newest first, in
napalm-device-types' ``LoginSessionsDict``; see the module.
:raises LoginSessionsUnavailable: when the host does not audit logons.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_SESSIONS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login session reading came back empty")
return parse_login_sessions(raw)
+14
View File
@@ -0,0 +1,14 @@
"""Who can log in to a Windows host and who did, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginsMixin` is both readings, :mod:`napalm_windows.login_accounts` and
:mod:`napalm_windows.login_sessions`, as one base of the driver.
"""
from __future__ import annotations
from napalm_windows.login_accounts import WindowsLoginAccountsMixin
from napalm_windows.login_sessions import WindowsLoginSessionsMixin
class WindowsLoginsMixin(WindowsLoginAccountsMixin, WindowsLoginSessionsMixin):
"""``get_login_accounts`` and ``get_login_sessions``; the driver carries the scripts."""
+143
View File
@@ -0,0 +1,143 @@
"""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"))
+119
View File
@@ -0,0 +1,119 @@
"""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))
+353
View File
@@ -0,0 +1,353 @@
"""A Windows host's security posture as the hardening reading (NetOrk/netork#2893).
:class:`WindowsPostureMixin` gives the driver napalm-device-types' ``get_hardening``,
filled with the posture keys of ``HardeningDict``; what only a Linux kernel has (the
security modules, the crypto policy, the CPU vulnerabilities, the command line) is
``None``. One script, read-only, six parts, each caught on its own so one that fails
leaves the others standing; a part that failed, or a cmdlet the host lacks, is ``None``:
not read, never "off".
- **Secure Boot:** ``Confirm-SecureBootUEFI``. On a BIOS boot it throws
``PlatformNotSupportedException``, which is ``unsupported``, not off.
- **TPM:** ``Win32_Tpm`` in ``root\\cimv2\\Security\\MicrosoftTpm``; no instance is no TPM.
- **BitLocker:** ``Win32_EncryptableVolume`` in
``root\\cimv2\\Security\\MicrosoftVolumeEncryption``: protection, conversion status,
cipher and volume type, per volume with a drive letter. Never ``Get-BitLockerVolume``,
whose objects carry the key protectors with their recovery passwords: the CIM class's
properties carry no secret. Where the class is missing, the BitLocker feature is not
installed (Windows Server's default): ``installed`` False, not an error.
- **Defender:** ``Get-MpComputerStatus``: the service and the engine, real-time
protection, the running mode (``Passive Mode`` and ``EDR Block Mode`` when another
product protects the host), the signatures' date, age and version, tamper protection.
Missing on Server Core without the Defender feature; it throws where Defender is
switched off for another product. Both are ``None``: no product is judged here.
- **Firewall profiles:** ``Get-NetFirewallProfile -PolicyStore ActiveStore``, the
effective state of each profile after group policy. On or off only: the rules are
the host firewall reading's.
- **VBS:** ``Win32_DeviceGuard`` in ``root\\Microsoft\\Windows\\DeviceGuard``: whether
virtualization-based security runs, and which of its services.
The cmdlets are probed with ``Get-Command`` first, so a missing one is not read rather
than an error. Most parts need an administrator; as another user they fail on their own.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any
from napalm_device_types.hardening import (
AntimalwareDict,
AntimalwareMode,
DiskEncryptionDict,
EncryptedVolumeDict,
FirewallProfileDict,
HardeningDict,
SecureBootState,
TpmDict,
VbsDict,
VbsStatus,
VolumeProtection,
)
from napalm_windows._powershell import _as_list
logger = logging.getLogger(__name__)
_PS_POSTURE = r"""
$ErrorActionPreference = 'Stop'
function Has([string]$name) { [bool](Get-Command -Name $name -ErrorAction SilentlyContinue) }
function Unix($when) {
if ($when) { [int64]([datetimeoffset]$when).ToUnixTimeSeconds() } else { $null }
}
$errors = [ordered]@{}
$secureBoot = $null
if (Has 'Confirm-SecureBootUEFI') {
try { $secureBoot = [string][bool](Confirm-SecureBootUEFI) }
catch {
if ($_.Exception -is [System.PlatformNotSupportedException] -or
[string]$_.FullyQualifiedErrorId -like '*PlatformNotSupported*') {
$secureBoot = 'unsupported'
} else { $errors.secure_boot = [string]$_.Exception.Message }
}
}
$tpm = $null
try {
$t = Get-CimInstance -Namespace 'root\cimv2\Security\MicrosoftTpm' -ClassName Win32_Tpm |
Select-Object -First 1
if ($t) {
$tpm = [pscustomobject]@{
present = $true
enabled = $t.IsEnabled_InitialValue
activated = $t.IsActivated_InitialValue
owned = $t.IsOwned_InitialValue
spec_version = [string]$t.SpecVersion
manufacturer = [string]$t.ManufacturerIdTxt
}
} else { $tpm = [pscustomobject]@{ present = $false } }
} catch { $errors.tpm = [string]$_.Exception.Message }
$bitlocker = $null
$bde = 'root\cimv2\Security\MicrosoftVolumeEncryption'
$probe = @{
Namespace = $bde; ClassName = 'Win32_EncryptableVolume'; ErrorAction = 'SilentlyContinue'
}
try {
if (Get-CimClass @probe) {
$bitlocker = [pscustomobject]@{
installed = $true
volumes = @(Get-CimInstance -Namespace $bde -ClassName Win32_EncryptableVolume |
ForEach-Object {
[pscustomobject]@{
drive = $_.DriveLetter
volume_type = [string]$_.VolumeType
protection = [string]$_.ProtectionStatus
conversion = [string]$_.ConversionStatus
method = [string]$_.EncryptionMethod
}
})
}
} else { $bitlocker = [pscustomobject]@{ installed = $false; volumes = @() } }
} catch { $errors.bitlocker = [string]$_.Exception.Message }
$defender = $null
if (Has 'Get-MpComputerStatus') {
try {
$mp = Get-MpComputerStatus
$defender = [pscustomobject]@{
am_service = $mp.AMServiceEnabled
antivirus = $mp.AntivirusEnabled
real_time = $mp.RealTimeProtectionEnabled
running_mode = [string]$mp.AMRunningMode
signature_updated = Unix $mp.AntivirusSignatureLastUpdated
signature_age = $mp.AntivirusSignatureAge
signature_version = [string]$mp.AntivirusSignatureVersion
tamper_protected = $mp.IsTamperProtected
}
} catch { $errors.defender = [string]$_.Exception.Message }
}
$firewall = $null
if (Has 'Get-NetFirewallProfile') {
try {
$firewall = @(Get-NetFirewallProfile -PolicyStore ActiveStore | ForEach-Object {
[pscustomobject]@{ name = [string]$_.Name; enabled = [string]$_.Enabled }
})
} catch { $errors.firewall = [string]$_.Exception.Message }
}
$vbs = $null
try {
$dg = Get-CimInstance -Namespace 'root\Microsoft\Windows\DeviceGuard' `
-ClassName Win32_DeviceGuard | Select-Object -First 1
if ($dg) {
$vbs = [pscustomobject]@{
status = [string]$dg.VirtualizationBasedSecurityStatus
running = @($dg.SecurityServicesRunning | ForEach-Object { [string]$_ })
}
}
} catch { $errors.vbs = [string]$_.Exception.Message }
[pscustomobject]@{
system_drive = $env:SystemDrive
secure_boot = $secureBoot
tpm = $tpm
bitlocker = $bitlocker
defender = $defender
firewall = $firewall
vbs = $vbs
errors = $errors
} | ConvertTo-Json -Compress -Depth 5
"""
_SECURE_BOOT: dict[str, SecureBootState] = {
"true": "on",
"false": "off",
"unsupported": "unsupported",
}
#: Win32_EncryptableVolume.ProtectionStatus
_PROTECTION: dict[str, VolumeProtection] = {"0": "off", "1": "on", "2": "unknown"}
#: Win32_EncryptableVolume.ConversionStatus
_CONVERSION = {
"0": "fully_decrypted",
"1": "fully_encrypted",
"2": "encrypting",
"3": "decrypting",
"4": "encryption_paused",
"5": "decryption_paused",
}
#: Win32_EncryptableVolume.EncryptionMethod; 0 is none.
_CIPHER = {
"1": "aes_128_diffuser",
"2": "aes_256_diffuser",
"3": "aes_128",
"4": "aes_256",
"5": "hardware",
"6": "xts_aes_128",
"7": "xts_aes_256",
}
#: Win32_EncryptableVolume.VolumeType: the volume the OS runs from.
_OS_VOLUME = "0"
#: MSFT_MpComputerStatus.AMRunningMode
_MODES: dict[str, AntimalwareMode] = {
"normal": "active",
"passive mode": "passive",
"passive": "passive",
"edr block mode": "edr_block",
"sxs passive mode": "sxs_passive",
}
#: Win32_DeviceGuard.VirtualizationBasedSecurityStatus
_VBS_STATUS: dict[str, VbsStatus] = {"0": "off", "1": "configured", "2": "running"}
#: Win32_DeviceGuard.SecurityServicesRunning; 0 is none.
_VBS_SERVICES = {
"1": "credential_guard",
"2": "hvci",
"3": "system_guard",
"4": "smm_firmware_measurement",
"5": "kernel_shadow_stacks",
"6": "kernel_shadow_stacks_audit",
"7": "hypervisor_paging_translation",
}
_GPO_BOOLEAN = {"true": True, "false": False}
def _text(value: Any) -> str | None:
text = str(value).strip() if value is not None else ""
return text or None
def _flag(value: Any) -> bool | None:
return value if isinstance(value, bool) else None
def _number(value: Any) -> int | None:
return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
def _secure_boot(value: Any) -> SecureBootState | None:
return _SECURE_BOOT.get(str(value).lower()) if value is not None else None
def _tpm_version(spec: Any) -> str | None:
"""``SpecVersion`` is ``"2.0, 0, 1.59"``: the specification's version comes first."""
return _text(str(spec or "").split(",", 1)[0])
def _tpm(raw: Any) -> TpmDict | None:
if not isinstance(raw, dict):
return None
return {
"present": bool(raw.get("present")),
"enabled": _flag(raw.get("enabled")),
"activated": _flag(raw.get("activated")),
"owned": _flag(raw.get("owned")),
"version": _tpm_version(raw.get("spec_version")),
"manufacturer": _text(raw.get("manufacturer")),
}
def _volume(raw: dict[str, Any], system_drive: str) -> EncryptedVolumeDict | None:
drive = _text(raw.get("drive"))
if drive is None:
return None # a recovery or boot partition: nothing is stored on it
return {
"volume": drive,
"system": str(raw.get("volume_type")) == _OS_VOLUME or drive.upper() == system_drive,
"protection": _PROTECTION.get(str(raw.get("protection")), "unknown"),
"status": _CONVERSION.get(str(raw.get("conversion"))),
"method": _CIPHER.get(str(raw.get("method"))),
}
def _disk_encryption(raw: Any, system_drive: str) -> DiskEncryptionDict | None:
if not isinstance(raw, dict):
return None
volumes = [
volume
for item in _as_list(raw.get("volumes"))
if isinstance(item, dict) and (volume := _volume(item, system_drive)) is not None
]
return {"provider": "bitlocker", "installed": bool(raw.get("installed")), "volumes": volumes}
def _antimalware(raw: Any) -> AntimalwareDict | None:
if not isinstance(raw, dict):
return None
service, engine = _flag(raw.get("am_service")), _flag(raw.get("antivirus"))
return {
"product": "Microsoft Defender Antivirus",
"enabled": False if service is False else engine,
"real_time": _flag(raw.get("real_time")),
"mode": _MODES.get(str(raw.get("running_mode") or "").strip().lower()),
"signatures_updated": _number(raw.get("signature_updated")),
"signature_age_days": _number(raw.get("signature_age")),
"signature_version": _text(raw.get("signature_version")),
"tamper_protected": _flag(raw.get("tamper_protected")),
}
def _firewall_profiles(raw: Any) -> list[FirewallProfileDict] | None:
if raw is None:
return None
return [
{
"name": str(item.get("name") or "").lower(),
"enabled": _GPO_BOOLEAN.get(str(item.get("enabled")).lower()),
}
for item in _as_list(raw)
if isinstance(item, dict)
]
def _vbs(raw: Any) -> VbsDict | None:
if not isinstance(raw, dict):
return None
running = [str(code) for code in _as_list(raw.get("running")) if str(code) != "0"]
return {
"status": _VBS_STATUS.get(str(raw.get("status"))),
"running": [_VBS_SERVICES.get(code, f"service_{code}") for code in running],
}
def parse_posture(raw: dict[str, Any]) -> HardeningDict:
"""The hardening reading from what :data:`_PS_POSTURE` emitted."""
for part, error in (raw.get("errors") or {}).items():
logger.info("posture: %s not read: %s", part, error)
system_drive = str(raw.get("system_drive") or "C:").upper()
reading: HardeningDict = {
"lsm": None,
"selinux": None,
"apparmor": None,
"crypto_policy": None,
"fips": None,
"cpu_vulnerabilities": None,
"cmdline": None,
"mitigations": None,
"nosmt": None,
"os_ids": None,
"virtualization": None,
"cpu_vendor": None,
"secure_boot": _secure_boot(raw.get("secure_boot")),
"tpm": _tpm(raw.get("tpm")),
"disk_encryption": _disk_encryption(raw.get("bitlocker"), system_drive),
"antimalware": _antimalware(raw.get("defender")),
"firewall_profiles": _firewall_profiles(raw.get("firewall")),
"vbs": _vbs(raw.get("vbs")),
}
return reading
class WindowsPostureMixin:
"""``get_hardening`` for a Windows host: its security posture; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_hardening(self) -> HardeningDict:
"""Secure Boot, the TPM, BitLocker per volume, Defender, the firewall's profiles and
virtualization-based security, in one round trip; see the module.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_POSTURE).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the posture reading came back empty")
return parse_posture(raw)
+159
View File
@@ -0,0 +1,159 @@
"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889).
:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes``
(``ProcessDict``). One script reads two sources and the join happens here:
* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time
(``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and
``VirtualSize``. Read first: it is the list.
* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a
``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM
administrator has; without one the script falls back to ``Get-Process`` and the owner
is unknown (empty).
A process is reported only when both saw it with the same start: one that exited between
the two reads is dropped rather than half-filled, and a PID reused in between is another
process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves
it out.
The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per
logical processor, so 0-100; ``memory`` the working set over the visible memory;
``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local
time. Windows has no controlling terminal and no process state of that kind: ``tty``
and ``state`` are empty. A process without a readable command line (``System``,
protected processes) shows its image name. Command lines are reported as the host
gives them, as ``ps`` does on Linux.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
from napalm_device_types.models import ProcessDict
from napalm_windows._powershell import _as_list
from napalm_windows._reading import json_object
_PS_PROCESSES = r"""
$ErrorActionPreference = 'Stop'
function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } }
function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } }
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object {
[pscustomobject]@{
pid = [int]$_.ProcessId
ppid = [int]$_.ParentProcessId
name = [string]$_.Name
command = [string]$_.CommandLine
started = Unix $_.CreationDate
offset = Offset $_.CreationDate
cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime
ws = [int64]$_.WorkingSetSize
vsz = [int64]$_.VirtualSize
}
})
try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) }
$owners = @($running | ForEach-Object {
$start = $null
try { $start = Unix $_.StartTime } catch { }
[pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start }
})
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{
now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
cores = [int]$cs.NumberOfLogicalProcessors
memory_kib = [int64]$os.TotalVisibleMemorySize
processes = $processes
owners = $owners
})
"""
#: How far the two sources' starts of one process may differ: they round differently.
_SAME_START = 2
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def _lstart(started: int | None, offset_minutes: int) -> str:
"""Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale."""
if started is None:
return ""
t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes)
return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}"
class _Host:
"""What the reading says about the host as a whole."""
def __init__(self, raw: dict[str, Any]) -> None:
self.now = int(raw.get("now") or 0)
self.cores = max(int(raw.get("cores") or 1), 1)
self.memory_kib = int(raw.get("memory_kib") or 0)
def cpu(self, cpu_100ns: int, started: int | None) -> float:
if started is None:
return 0.0
elapsed = max(self.now - started, 1)
return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1)
def memory(self, rss_kib: int) -> float:
return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0
def _started(entry: dict[str, Any]) -> int | None:
value = entry.get("started")
return int(value) if value is not None else None
def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool:
"""False when ``Get-Process`` saw another start under this PID: it was reused."""
ours, theirs = _started(entry), _started(owner)
return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START
def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict:
started = _started(entry)
rss = int(entry.get("ws") or 0) // 1024
return {
"pid": int(entry["pid"]),
"ppid": int(entry.get("ppid") or 0),
"user": str(owner.get("user") or ""),
"cpu": host.cpu(int(entry.get("cpu") or 0), started),
"memory": host.memory(rss),
"vsz": int(entry.get("vsz") or 0) // 1024,
"rss": rss,
"tty": "",
"state": "",
"started": _lstart(started, int(entry.get("offset") or 0)),
"command": str(entry.get("command") or entry.get("name") or ""),
}
def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]:
"""``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join."""
host = _Host(raw)
owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))}
processes = []
for entry in _as_list(raw.get("processes")):
owner = owners.get(int(entry["pid"]))
if not entry["pid"] or owner is None or not _same_process(entry, owner):
continue
processes.append(_process(entry, owner, host))
return sorted(processes, key=lambda p: p["pid"])
class WindowsProcessesMixin:
"""``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries
the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_processes(self) -> list[ProcessDict]:
"""A snapshot of the running processes, shaped like ``ps``; see the module.
:raises ValueError: when the reading came back empty.
"""
return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))
+268
View File
@@ -0,0 +1,268 @@
"""Repair runs on Windows: SFC, DISM and Microsoft Defender (NetOrk/netork#2899).
:class:`WindowsRepairsMixin` implements the runs of napalm-device-types'
:class:`~napalm_device_types.host_repairs.HostRepairMixin` this driver can do:
================================== ===============================================
``verify_system_files`` ``sfc /verifyonly``
``check_component_store`` ``DISM /Online /Cleanup-Image /ScanHealth``
``update_antimalware_signatures`` ``Update-MpSignature``
``scan_antimalware`` ``Start-MpScan -ScanType QuickScan|FullScan``
================================== ===============================================
The two repairs, ``sfc /scannow`` and ``DISM /RestoreHealth``, are not defined, so the
driver does not offer them: in a remote session ``sfc /scannow`` may fail to start the
repair service (TrustedInstaller), and ``RestoreHealth`` needs a repair source that
WSUS-managed hosts often lack. Both wait for a test on a real host.
**One bounded PSRP call per run.** Each run is one script streamed over the open
connection (``PsrpTransport.run_streaming``): its lines reach ``log`` as the host
prints them, and a run still going after its limit is stopped. The tools run as the
connection's administrator, not through a SYSTEM scheduled task; should a real host
show that a tool needs SYSTEM, the task building block of
:mod:`napalm_windows.scheduled_tasks` is where it would move.
**Native tools** start as a process whose output is read line by line in the encoding
the tool writes: ``sfc`` writes UTF-16 to a redirected stdout, read as such; DISM
writes the OEM code page and runs with ``/English``, so its words are the same on
every host. Should text still arrive as UTF-16 read byte by byte, :func:`tool_lines`
drops the NULs between the characters. A tool missing from the host says
``napalm-not-available:<tool>``; every script ends with ``napalm-exit-code:<n>``.
Neither line reaches ``log``. The exit code decides (``tool_outcome``): 0 succeeds, any
other fails with the tool's last lines. A check that finds damage may still end with 0;
the verdict is in its output.
**Defender** runs only where ``Get-Command`` finds its cmdlets, so a host with another
antivirus (or Server without the feature) fails with "not available", not an error.
The signature update names the version before and after; a scan names what it
detected since it started, handled as Defender is set to handle it.
Nothing here restarts the host or creates a restore point.
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from napalm.base.exceptions import ConnectionClosedException
from napalm_device_types import HostRepairMixin, HostRepairResultDict, tool_outcome
from napalm_device_types.host_repairs import LineLog
from napalm_windows.transport import PowerShellError
if TYPE_CHECKING: # pragma: no cover - for type checkers only
from napalm_windows.transport import PsrpTransport
#: The longest each run may take, in seconds; a caller's ``limit`` can only tighten it.
SFC_LIMIT = 3600
DISM_LIMIT = 3600
SIGNATURE_LIMIT = 900
QUICK_SCAN_LIMIT = 3600
FULL_SCAN_LIMIT = 4 * 3600
_EXIT = "napalm-exit-code:"
_MISSING = "napalm-not-available:"
_LINE_BREAKS = re.compile(r"\r\n|\r|\n")
# A native tool as a process, its stdout read line by line in the tool's encoding and
# written to the pipeline as it comes, its stderr after it. No console is involved, so
# nothing depends on the remote session's console code page.
_PS_NATIVE = r"""
$ErrorActionPreference = 'Stop'
function Invoke-NativeTool([string]$Path, [string]$Arguments, [System.Text.Encoding]$Encoding) {
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
'napalm-not-available:' + (Split-Path -Leaf $Path)
return
}
$info = New-Object System.Diagnostics.ProcessStartInfo
$info.FileName = $Path
$info.Arguments = $Arguments
$info.UseShellExecute = $false
$info.CreateNoWindow = $true
$info.RedirectStandardOutput = $true
$info.RedirectStandardError = $true
$info.StandardOutputEncoding = $Encoding
$info.StandardErrorEncoding = $Encoding
$process = [System.Diagnostics.Process]::Start($info)
$errors = $process.StandardError.ReadToEndAsync()
while ($null -ne ($line = $process.StandardOutput.ReadLine())) { $line }
$process.WaitForExit()
$errors.Result -split "`r?`n" | Where-Object { $_ }
'napalm-exit-code:' + $process.ExitCode
}
"""
_PS_SFC_VERIFY = (
_PS_NATIVE
+ r"""
$sfc = Join-Path $env:SystemRoot 'System32\sfc.exe'
Invoke-NativeTool $sfc '/verifyonly' ([System.Text.Encoding]::Unicode)
"""
)
_PS_DISM_SCAN = (
_PS_NATIVE
+ r"""
$page = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage
$dism = Join-Path $env:SystemRoot 'System32\Dism.exe'
$arguments = '/Online /Cleanup-Image /ScanHealth /English'
Invoke-NativeTool $dism $arguments ([System.Text.Encoding]::GetEncoding($page))
"""
)
_PS_SIGNATURE_UPDATE = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Update-MpSignature -ErrorAction SilentlyContinue)) {
'napalm-not-available:Microsoft Defender Antivirus'
return
}
function Get-SignatureLine([string]$When) {
try {
$status = Get-MpComputerStatus
$at = ([datetime]$status.AntivirusSignatureLastUpdated).ToUniversalTime()
$at = $at.ToString('yyyy-MM-dd HH:mm')
$When + ': ' + [string]$status.AntivirusSignatureVersion + ', updated ' + $at + ' UTC'
} catch {
$When + ': not readable (' + $_.Exception.Message + ')'
}
}
Get-SignatureLine 'Signatures before'
$code = 0
try { Update-MpSignature } catch { 'Update-MpSignature failed: ' + $_.Exception.Message; $code = 1 }
Get-SignatureLine 'Signatures after'
'napalm-exit-code:' + $code
"""
# Start-MpScan returns when the scan ended. What it detected since it started is read
# from Defender's detections, by threat name and whether Defender's action went through.
_PS_SCAN = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Start-MpScan -ErrorAction SilentlyContinue)) {
'napalm-not-available:Microsoft Defender Antivirus'
return
}
$start = Get-Date
'Scan started: {scan_type}'
$code = 0
try {
Start-MpScan -ScanType {scan_type}
} catch {
'Start-MpScan failed: ' + $_.Exception.Message
$code = 1
}
'Scan ended.'
$found = @()
try {
$found = @(Get-MpThreatDetection | Where-Object { $_.InitialDetectionTime -ge $start })
} catch { }
'Threats detected: ' + $found.Count
foreach ($detection in $found) {
$name = [string]$detection.ThreatID
try { $name = [string](Get-MpThreat -ThreatID $detection.ThreatID).ThreatName } catch { }
$action = if ($detection.ActionSuccess) { 'succeeded' } else { 'not completed' }
' ' + $name + ': action ' + $action
}
'napalm-exit-code:' + $code
"""
_PS_QUICK_SCAN = _PS_SCAN.replace("{scan_type}", "QuickScan")
_PS_FULL_SCAN = _PS_SCAN.replace("{scan_type}", "FullScan")
def tool_lines(item: str) -> list[str]:
"""One output object of a run as lines: without NULs (UTF-16 read byte by byte) or a
byte order mark, split at every line break -- progress ends its lines with a bare
carriage return -- trailing spaces and blank lines dropped."""
text = item.replace("\x00", "").replace("", "")
return [line.rstrip() for line in _LINE_BREAKS.split(text) if line.strip()]
def _exit_code(text: str) -> int | None:
try:
return int(text.strip())
except ValueError:
return None
class _ToolRun:
"""What a run's script printed, its exit code and a missing tool, as it arrives."""
def __init__(self, log: LineLog | None) -> None:
self.log = log
self.lines: list[str] = []
self.exit_code: int | None = None
self.missing: str | None = None
def take(self, item: str) -> None:
for line in tool_lines(item):
if line.startswith(_EXIT):
self.exit_code = _exit_code(line.removeprefix(_EXIT))
elif line.startswith(_MISSING):
self.missing = line.removeprefix(_MISSING).strip()
else:
self.lines.append(line)
if self.log is not None:
self.log(line)
def outcome(self, tool: str) -> HostRepairResultDict:
if self.missing is not None:
return {
"success": False,
"output": "\n".join(self.lines),
"exit_code": None,
"error": f"{self.missing} is not available on this host",
}
return tool_outcome(self.lines, self.exit_code, tool=tool)
def cut_off(self, tool: str, why: str) -> HostRepairResultDict:
return tool_outcome([*self.lines, why], None, tool=tool)
class WindowsRepairsMixin(HostRepairMixin):
"""SFC, DISM and Defender runs for :class:`~napalm_windows.windows.WindowsDriver`."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
_transport: PsrpTransport | None
def verify_system_files(
self, *, log: LineLog | None = None, limit: float | None = None
) -> HostRepairResultDict:
"""``sfc /verifyonly``: checks the protected system files and changes nothing."""
return self._tool_run(_PS_SFC_VERIFY, "sfc /verifyonly", SFC_LIMIT, log, limit)
def check_component_store(
self, *, log: LineLog | None = None, limit: float | None = None
) -> HostRepairResultDict:
"""``DISM /Online /Cleanup-Image /ScanHealth``: scans the component store and
changes nothing; up to half an hour."""
return self._tool_run(_PS_DISM_SCAN, "DISM /ScanHealth", DISM_LIMIT, log, limit)
def update_antimalware_signatures(
self, *, log: LineLog | None = None, limit: float | None = None
) -> HostRepairResultDict:
"""``Update-MpSignature``, with the signature version before and after."""
return self._tool_run(
_PS_SIGNATURE_UPDATE, "Update-MpSignature", SIGNATURE_LIMIT, log, limit
)
def scan_antimalware(
self, quick: bool = True, *, log: LineLog | None = None, limit: float | None = None
) -> HostRepairResultDict:
"""``Start-MpScan``, quick or full, with what it detected."""
if quick:
return self._tool_run(_PS_QUICK_SCAN, "Start-MpScan", QUICK_SCAN_LIMIT, log, limit)
return self._tool_run(_PS_FULL_SCAN, "Start-MpScan", FULL_SCAN_LIMIT, log, limit)
def _tool_run(
self, script: str, tool: str, bound: float, log: LineLog | None, limit: float | None
) -> HostRepairResultDict:
"""Run *script*; within *bound*, or the caller's *limit* where that is tighter."""
limit = bound if limit is None else min(limit, bound)
if self._transport is None:
raise ConnectionClosedException("WinRM connection is not open")
run = _ToolRun(log)
try:
self._transport.run_streaming(script, run.take, limit=limit)
except (TimeoutError, PowerShellError) as exc:
return run.cut_off(tool, str(exc))
return run.outcome(tool)
+475
View File
@@ -0,0 +1,475 @@
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
:class:`WindowsScheduledJobsMixin` implements napalm-device-types'
:class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` for the driver,
which carries each script across ``PsrpTransport.run``.
**Reading** is one script: every task (``Get-ScheduledTask``) with what the host
says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and the
host's time zone; Python only normalises. Every task is a job ``task:<path><name>``
whose schedule is a summary of its triggers. A task under ``\\Microsoft\\`` is the
``platform``'s, any other the ``admin``'s -- Windows does not say which software
installed a task -- except the driver's own Windows Update runs under
``\\napalm-windows\\``, an ``application``'s that offer nothing; and a task in the root
folder whose description starts with ``napalm-scheduled-job: <its name>`` is an
``application``'s, read back as the cron expression and command it was written with
(:mod:`napalm_windows.task_xml`). Its
digest covers its triggers as well, so triggers changed by hand are a change. A
reading whose task count does not match, or whose JSON is cut short, raises.
**Switching** is the task's own flag (``Enable-`` / ``Disable-ScheduledTask``);
**running** is ``Start-ScheduledTask``, which returns once the task has started: how
the run ends shows in the next reading. A disabled task, or one that does not allow a
start on demand, is not offered ``run``. A task is addressed by its exact path and
name, never by ``-TaskName``, which takes wildcards.
**An application's own job** is registered from XML (``Register-ScheduledTask -Xml
-Force``), so creating it and changing it write the whole definition the same way;
``delete_scheduled_job`` unregisters it. Before every write the job is read again
and compared with the digest the caller saw; a task of the same name that an
application did not write is never overwritten. Every value goes into PowerShell
single-quoted, its quotes doubled.
"""
from __future__ import annotations
import json
import re
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_device_types import (
ScheduledJobChanged,
ScheduledJobDict,
ScheduledJobRefused,
ScheduledJobResultDict,
ScheduledJobsMixin,
ScheduledJobSpecDict,
ScheduledJobsReadingDict,
job_digest,
)
from napalm_device_types.scheduled_jobs import ACTIONS, DELETE, EDIT, check_spec
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.task_xml import JOB_MARKER, SCHEDULE_LINE, own_command, task_xml
from napalm_windows.time_zones import iana_time_zone
from napalm_windows.transport import PowerShellError
from napalm_windows.windows_update_run import TASK_PATH
# Every task with its run info. Times leave the host as ISO 8601 in UTC; a task
# whose run info cannot be read keeps its definition and loses only its times.
_PS_SCHEDULED_TASKS = r"""
$ErrorActionPreference = 'Stop'
function U($d) { if ($d) { ([datetime]$d).ToUniversalTime().ToString('o') } }
$tasks = @(Get-ScheduledTask)
$rows = @($tasks | ForEach-Object {
$t = $_
$i = $t | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
[pscustomobject]@{
path = $t.TaskPath
name = $t.TaskName
state = [string]$t.State
user = $t.Principal.UserId
group = $t.Principal.GroupId
on_demand = $t.Settings.AllowDemandStart
description = $t.Description
actions = @($t.Actions | ForEach-Object {
[pscustomobject]@{
class = $_.CimClass.CimClassName
execute = $_.Execute
arguments = $_.Arguments
class_id = $_.ClassId
}
})
triggers = @($t.Triggers | ForEach-Object {
[pscustomobject]@{
class = $_.CimClass.CimClassName
enabled = $_.Enabled
start = [string]$_.StartBoundary
days_interval = $_.DaysInterval
weeks_interval = $_.WeeksInterval
days_of_week = $_.DaysOfWeek
interval = [string]$_.Repetition.Interval
duration = [string]$_.Repetition.Duration
delay = [string]$_.Delay
}
})
last_run = U $i.LastRunTime
last_result = $i.LastTaskResult
next_run = U $i.NextRunTime
}
})
ConvertTo-Json -Compress -Depth 5 -InputObject ([pscustomobject]@{
time_zone = [System.TimeZoneInfo]::Local.Id
count = $tasks.Count
tasks = $rows
})
"""
# One task by its exact path and name, handed to a cmdlet.
_PS_TASK_CMDLET = r"""
$ErrorActionPreference = 'Stop'
$task = @(Get-ScheduledTask | Where-Object {{ $_.TaskPath -eq {path} -and $_.TaskName -eq {name} }})
if ($task.Count -ne 1) {{ throw ('no single scheduled task ' + {path} + {name}) }}
$task[0] | {cmdlet} | Out-Null
"""
_PS_REGISTER = r"""
$ErrorActionPreference = 'Stop'
Register-ScheduledTask -TaskPath {path} -TaskName {name} -Xml {xml} -Force | Out-Null
"""
_PS_UNREGISTER = r"""
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskPath {path} -TaskName {name} -Confirm:$false
"""
_CMDLETS = {
"enable": ("Enable-ScheduledTask", "enabled"),
"disable": ("Disable-ScheduledTask", "disabled"),
"run": (
"Start-ScheduledTask",
"started; Start-ScheduledTask returns once it has started, so how the run "
"ends shows in the next reading",
),
}
_ROOT = "\\"
_JOB_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
_DOTNET_DATE = re.compile(r"^/Date\((-?\d+)(?:[+-]\d{4})?\)/$")
_BOUNDARY = re.compile(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)(?::\d\d(?:\.\d+)?)?(Z|[+-]\d\d:\d\d)?$")
_DURATION = re.compile(r"^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$")
_DURATION_UNITS = ("day", "hour", "minute", "second")
#: LastTaskResult: SCHED_S_TASK_RUNNING and SCHED_S_TASK_HAS_NOT_RUN.
_RUNNING = 0x41301
_NEVER_RAN = 0x41303
_WEEKDAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
_EVENT_TRIGGERS = {
"MSFT_TaskBootTrigger": "at startup",
"MSFT_TaskLogonTrigger": "at logon",
"MSFT_TaskIdleTrigger": "on idle",
"MSFT_TaskEventTrigger": "on an event",
"MSFT_TaskSessionStateChangeTrigger": "session state change",
"MSFT_TaskRegistrationTrigger": "at registration",
}
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
def _timestamp(value: Any) -> str | None:
"""A time as the host gave it -- ISO 8601, ``/Date(ms)/`` or epoch seconds -- as
ISO 8601 in UTC; None for none, and for Task Scheduler's never (30 November 1999)."""
if value is None or value == "":
return None
if isinstance(value, int | float):
at = datetime.fromtimestamp(value, UTC)
elif match := _DOTNET_DATE.match(str(value).strip()):
at = datetime.fromtimestamp(int(match[1]) / 1000, UTC)
else:
try:
at = datetime.fromisoformat(str(value).strip())
except ValueError:
return None
at = (at if at.tzinfo else at.replace(tzinfo=UTC)).astimezone(UTC)
return None if at.year < 2000 else at.isoformat()
def _last_result(code: Any, last_run: str | None) -> str | None:
if last_run is None or code is None:
return None
code = int(code) & 0xFFFFFFFF
if code == _NEVER_RAN:
return None
if code == _RUNNING:
return "running"
return "success" if code == 0 else f"0x{code:X}"
def _readable_duration(value: str) -> str:
"""``PT1H30M`` → ``1 hour 30 minutes``; anything else as it is."""
match = _DURATION.match(value)
if not match or not any(match.groups()):
return value
parts = [
f"{n} {unit}{'' if n == '1' else 's'}"
for n, unit in zip(match.groups(), _DURATION_UNITS, strict=True)
if n
]
return " ".join(parts)
def _clock(start: str) -> tuple[str, str]:
"""A trigger's start boundary as its date and its time of day (with its offset)."""
match = _BOUNDARY.match(start)
if not match:
return "", start
return match[1], match[2] + (match[3] or "")
def _every(count: Any, unit: str) -> str:
return f"{unit}ly" if count in (None, 0, 1) else f"every {count} {unit}s"
def _calendar(trigger: dict[str, Any], cls: str) -> str:
date, time = _clock(str(trigger.get("start") or ""))
at = f" at {time}" if time else ""
if cls == "MSFT_TaskDailyTrigger":
days = trigger.get("days_interval")
return ("daily" if days in (None, 0, 1) else f"every {days} days") + at
if cls == "MSFT_TaskWeeklyTrigger":
mask = int(trigger.get("days_of_week") or 0)
days = ",".join(d for i, d in enumerate(_WEEKDAYS) if mask & (1 << i))
return f"{_every(trigger.get('weeks_interval'), 'week')} on {days}{at}"
if cls == "MSFT_TaskTimeTrigger":
return f"once at {date} {time}".rstrip()
return f"trigger{at}"
def _trigger(trigger: dict[str, Any]) -> str:
"""One trigger as a short sentence: its kind, when, how it repeats."""
cls = str(trigger.get("class") or "")
text = _EVENT_TRIGGERS.get(cls) or _calendar(trigger, cls)
if trigger.get("delay"):
text += f" after {_readable_duration(str(trigger['delay']))}"
if trigger.get("interval"):
text += f", every {_readable_duration(str(trigger['interval']))}"
if trigger.get("duration"):
text += f" for {_readable_duration(str(trigger['duration']))}"
if trigger.get("enabled") is False:
text += " (disabled)"
return text
def _action(action: dict[str, Any]) -> str:
if action.get("execute"):
return " ".join(str(p) for p in (action["execute"], action.get("arguments")) if p)
if action.get("class_id"):
return f"COM handler {action['class_id']}"
return str(action.get("class") or "")
class _Own(NamedTuple):
"""What an application's task description and action say of the job."""
name: str
description: str
schedule: str | None
command: str | None
def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None:
"""The application's job this task is; None for any other task."""
lines = str(task.get("description") or "").splitlines()
if path != _ROOT or not lines or not lines[0].startswith(JOB_MARKER):
return None
job_name, _, description = lines[0][len(JOB_MARKER) :].partition(" ")
if job_name != name or not _JOB_NAME.fullmatch(name):
return None
schedule = next(
(ln[len(SCHEDULE_LINE) :] for ln in lines[1:] if ln.startswith(SCHEDULE_LINE)), None
)
actions = _as_list(task.get("actions"))
command = (
own_command(actions[0].get("execute"), actions[0].get("arguments"))
if len(actions) == 1
else None
)
return _Own(name, description.strip(), schedule, command)
def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]:
if str(task.get("path") or "").lower() == TASK_PATH.lower():
return [] # an update run's task: deleted when its run ends
verbs = ["enable", "disable"]
if enabled and task.get("on_demand") is not False:
verbs.append("run")
return [*verbs, EDIT, DELETE] if own else verbs
class _Definition(NamedTuple):
"""What a task's fields say it does, as the job shows it."""
schedule: str
schedule_kind: str
command: str
managed_by: str
description: str
def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None) -> _Definition:
command = "\n".join(_action(a) for a in _as_list(task.get("actions")))
if own is not None:
kind = "cron" if own.schedule else "triggers"
return _Definition(
own.schedule or triggers, kind, own.command or command, "application", own.description
)
return _Definition(
triggers,
"triggers",
command,
_owner(path),
str(task.get("description") or "").strip(),
)
def _owner(path: str) -> str:
"""Who a task that no application wrote as a job belongs to, by its folder: the
platform's under ``\\Microsoft\\``, the driver's own update runs' under
:data:`~napalm_windows.windows_update_run.TASK_PATH`, any other the admin's."""
folder = path.lower()
if folder == TASK_PATH.lower():
return "application"
return "platform" if folder.startswith("\\microsoft\\") else "admin"
def _task_job(task: dict[str, Any]) -> ScheduledJobDict:
path, name = str(task.get("path") or _ROOT), str(task.get("name") or "")
triggers = "; ".join(_trigger(t) for t in _as_list(task.get("triggers")))
enabled = str(task.get("state") or "").lower() != "disabled"
own = _own(path, name, task)
found = _definition(path, task, triggers, own)
last_run = _timestamp(task.get("last_run"))
job: ScheduledJobDict = {
"key": f"task:{path}{name}",
"kind": "task",
"source": f"{path}{name}",
"run_as": str(task.get("user") or task.get("group") or ""),
"schedule": found.schedule,
"schedule_kind": found.schedule_kind,
"command": found.command,
"enabled": enabled,
"managed_by": found.managed_by,
"digest": "",
"actions": _verbs(task, enabled, own is not None),
"last_run": last_run,
"last_result": _last_result(task.get("last_result"), last_run),
"next_run": _timestamp(task.get("next_run")),
}
# An application's task shows its cron line; its triggers are what runs.
job["digest"] = job_digest(dict(job), content=triggers if own else "")
if own is not None:
job["name"] = own.name
if found.description:
job["description"] = found.description
return job
def parse_reading(output: str) -> tuple[list[ScheduledJobDict], str | None]:
"""The jobs and the IANA time zone in what :data:`_PS_SCHEDULED_TASKS` printed.
:raises ValueError: when the reading is cut short or holds fewer tasks than counted.
"""
raw = json.loads(output)
if not isinstance(raw, dict):
raise ValueError("not a scheduled-tasks reading")
tasks = _as_list(raw.get("tasks"))
count = int(raw.get("count") or 0)
if len(tasks) != count:
raise ValueError(f"the reading holds {len(tasks)} of {count} scheduled tasks")
return [_task_job(t) for t in tasks], iana_time_zone(raw.get("time_zone"))
def _path_and_name(source: str) -> tuple[str, str]:
path, _, name = source.rpartition("\\")
return path + "\\", name
# ---------------------------------------------------------------------------
# The mixin
# ---------------------------------------------------------------------------
class WindowsScheduledJobsMixin(ScheduledJobsMixin):
"""The Task Scheduler as scheduled jobs; the driver carries the scripts."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _sj_read(self) -> tuple[list[ScheduledJobDict], str | None]:
return parse_reading(self._run_raw(_PS_SCHEDULED_TASKS))
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
"""Every task of the host, in one round trip.
:raises ValueError: when the reading came back cut short.
"""
jobs, time_zone = self._sj_read()
return {"jobs": jobs, "time_zone": time_zone}
def _sj_job(self, key: str, digest: str) -> ScheduledJobDict:
jobs, _ = self._sj_read()
job = next((j for j in jobs if j["key"] == key), None)
if job is None:
raise LookupError(f"no scheduled job {key}")
if job["digest"] != digest:
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
return job
def _sj_send(self, script: str, done: str) -> ScheduledJobResultDict:
try:
self._run_raw(script)
except PowerShellError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": done}
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
"""Enable, disable or start the task *key*; see :class:`ScheduledJobsMixin`."""
if action not in ACTIONS:
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
job = self._sj_job(key, digest)
if action not in job["actions"]:
raise ScheduledJobRefused(
f"{key} cannot be told to {action}: it is disabled or "
"does not allow a start on demand"
)
cmdlet, done = _CMDLETS[action]
path, name = _path_and_name(job["source"])
script = _PS_TASK_CMDLET.format(path=_ps_quote(path), name=_ps_quote(name), cmdlet=cmdlet)
return self._sj_send(script, f"{key} {done}")
def _sj_own(self, spec: ScheduledJobSpecDict, digest: str | None) -> ScheduledJobDict | None:
key = f"task:{_ROOT}{spec['name']}"
jobs, _ = self._sj_read()
# Task names are case-insensitive: Register -Force would replace "\Name" too.
current = next((j for j in jobs if j["key"].lower() == key), None)
if digest is None:
if current is not None:
raise ScheduledJobChanged(f"a task {current['source']} is there already")
return None
if current is None:
raise LookupError(f"no scheduled job {key}")
if current["managed_by"] != "application":
raise ScheduledJobRefused(f"{current['key']} was not written by an application")
if current["digest"] != digest:
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
return current
def put_scheduled_job(
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
) -> ScheduledJobResultDict:
"""Register or change the application's own task; see :class:`ScheduledJobsMixin`."""
check_spec(spec)
xml = task_xml(spec)
current = self._sj_own(spec, digest)
script = _PS_REGISTER.format(
path=_ps_quote(_ROOT), name=_ps_quote(spec["name"]), xml=_ps_quote(xml)
)
verb = "changed" if current else "created"
return self._sj_send(script, f"task:{_ROOT}{spec['name']} {verb}")
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
"""Unregister the application's task *key*; see :class:`ScheduledJobsMixin`."""
job = self._sj_job(key, digest)
if job["managed_by"] != "application":
raise ScheduledJobRefused(
f"{key} was not written by an application; it is only switched"
)
path, name = _path_and_name(job["source"])
script = _PS_UNREGISTER.format(path=_ps_quote(path), name=_ps_quote(name))
return self._sj_send(script, f"{key} deleted")
+98
View File
@@ -0,0 +1,98 @@
"""The host's services, and how each one's last run ended (NetOrk/netork#2897).
:class:`WindowsServicesMixin` reads ``get_services`` for the driver, which carries
the script across ``PsrpTransport.run``.
One script: every ``Win32_Service`` with its state, start mode and process, the
account it runs as (``StartName``) and the code its last run ended with
(``ExitCode``). Both exit codes are UInt32 and leave the host as ``[int64]``, since
``[int]`` would throw on an HRESULT and fail the reading. Which services a trigger
starts (a device arriving, a network change, a request) is one registry read for all
of them: the ``TriggerInfo`` keys under ``HKLM:\\SYSTEM\\CurrentControlSet\\Services``.
**How the last run ended** is said in systemd's words (napalm-device-types'
``ServiceDict.result``), so that one rule reads it for every host:
* ``0`` is ``success``: running, or stopped on purpose.
* ``1077`` (``ERROR_SERVICE_NEVER_STARTED``) is no result: not started since the
host booted -- a demand-start service, or a delayed one in the minutes after boot.
* ``1066`` (``ERROR_SERVICE_SPECIFIC_ERROR``) is ``exit-code`` with the service's own
code, ``ServiceSpecificExitCode``.
* Any other code is ``exit-code`` with that code: ``1067`` is a process that ended
without being stopped.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict
from napalm_windows._powershell import _as_list
_PS_SERVICES = r"""
$ErrorActionPreference = 'Stop'
$triggered = @{}
$keys = 'HKLM:\SYSTEM\CurrentControlSet\Services\*\TriggerInfo'
Get-Item -Path $keys -ErrorAction SilentlyContinue |
ForEach-Object { $triggered[(Split-Path -Path $_.PSParentPath -Leaf)] = $true }
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
[pscustomobject]@{
name = $_.Name
state = [string]$_.State
start_mode = [string]$_.StartMode
pid = [int]$_.ProcessId
exit_code = [int64]$_.ExitCode
service_code = [int64]$_.ServiceSpecificExitCode
account = $_.StartName
trigger_start = [bool]$triggered[$_.Name]
}
}
)
"""
_ENABLED_START_MODES = {"auto", "boot", "system"}
#: ``ERROR_SERVICE_NEVER_STARTED``: no attempt to start it since the host booted.
_NEVER_STARTED = 1077
#: ``ERROR_SERVICE_SPECIFIC_ERROR``: the code is the service's own.
_SERVICE_SPECIFIC = 1066
def _result(raw: dict[str, Any]) -> tuple[str | None, int | None]:
"""How the last run ended, and its code where that was not success."""
code = raw.get("exit_code")
if code is None or int(code) == _NEVER_STARTED:
return None, None
if int(code) == 0:
return SERVICE_RESULT_SUCCESS, None
if int(code) == _SERVICE_SPECIFIC and raw.get("service_code"):
return SERVICE_RESULT_EXIT_CODE, int(raw["service_code"])
return SERVICE_RESULT_EXIT_CODE, int(code)
def _service(raw: dict[str, Any]) -> ServiceDict:
running = str(raw.get("state") or "").lower() == "running"
result, exit_code = _result(raw)
return {
"name": str(raw["name"]),
"running": running,
"enabled": str(raw.get("start_mode") or "").lower() in _ENABLED_START_MODES,
"pid": int(raw.get("pid") or 0) if running else 0,
"result": result,
"exit_code": exit_code,
"trigger_start": bool(raw.get("trigger_start")),
"account": str(raw["account"]) if raw.get("account") else None,
}
class WindowsServicesMixin:
"""``get_services`` from ``Win32_Service``; 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_services(self) -> list[ServiceDict]:
"""Every service with whether it runs, starts at boot, and how its last run ended."""
return [_service(s) for s in _as_list(self._run_ps(_PS_SERVICES))]
+355
View File
@@ -0,0 +1,355 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
:class:`WindowsStorageMixin` implements napalm-device-types'
:class:`~napalm_device_types.host_storage.HostStorageMixin` for the driver, which carries
each script across ``PsrpTransport.run``. A Windows host has disks; it is not a storage
device, so the getters come with no role and the driver stays ``windows``.
Everything is read from the Storage module's CIM classes, the same on every Windows
Server 2016+ and Windows 10/11, without installing anything:
- **Disks** are ``Get-PhysicalDisk``: model, serial, medium (``MediaType``), bus
(``BusType``; NVMe is a type of its own) and Windows' verdict (``HealthStatus``). A
Storage Spaces virtual disk (``BusType`` ``Spaces``) is built from other disks and is no
physical disk; its members are. Which pool a disk belongs to is
``Get-StoragePool -IsPrimordial $false`` with its member disks.
- **Drive health** is ``Get-StorageReliabilityCounter`` per disk: temperature, wear,
power-on hours, uncorrected read and write errors. It needs an administrator, and a
virtual disk often has none: a disk whose counter cannot be read has no counter, which
is "unknown", not an error. Windows writes ``0`` where a drive does not report a value,
so a zero temperature is none, and a disk whose counters are all empty reports nothing.
- **Health without a measurement is "unknown".** A disk whose medium Windows cannot tell
(``MediaType`` ``Unspecified``) and whose counters are empty is a virtual disk or a RAID
controller's logical disk; Windows calls it ``Healthy``, which says it is attached, not
that a drive is well. Its health reads ``unknown``. ``Warning`` and ``Unhealthy`` are
always passed on.
- **Pools** are Storage Spaces' ``Get-StoragePool -IsPrimordial $false``. Their size and
allocation are raw capacity: what is usable depends on each virtual disk's resiliency.
- **Volumes** are ``Get-Volume``'s fixed volumes, mounted at a drive letter or in a
folder (``Get-Partition``'s ``AccessPaths``). A volume mounted nowhere -- the EFI system
partition, the recovery partition -- is left out.
Each script asks ``Get-Command`` first, so a host without the Storage module answers "not
supported" (empty) rather than failing. Drive health is read with the disks, in one round
trip; ``get_disks`` and ``get_disk_smart`` each send it.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from napalm_device_types.host_storage import DiskSmartDict, HostStorageMixin, HostVolumeDict
from napalm_device_types.models import DiskPoolDict, LogicalVolumeDict, PhysicalDiskDict
from napalm_windows._powershell import _as_list
_PS_DISKS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-PhysicalDisk -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$readCounters = [bool](
Get-Command -Name Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
)
$pools = @{}
if (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue) {
try {
foreach ($pool in @(Get-StoragePool -IsPrimordial $false)) {
foreach ($member in @(Get-PhysicalDisk -StoragePool $pool)) {
$pools[[string]$member.UniqueId] = [string]$pool.FriendlyName
}
}
} catch { }
}
$disks = @(Get-PhysicalDisk | ForEach-Object {
$disk = $_
$counter = $null
if ($readCounters) {
try { $counter = $disk | Get-StorageReliabilityCounter } catch { $counter = $null }
}
[pscustomobject]@{
device_id = [string]$disk.DeviceId
unique_id = [string]$disk.UniqueId
name = [string]$disk.FriendlyName
model = [string]$disk.Model
vendor = [string]$disk.Manufacturer
serial = [string]$disk.SerialNumber
media_type = [string]$disk.MediaType
bus_type = [string]$disk.BusType
health = [string]$disk.HealthStatus
size = $disk.Size
spindle = $disk.SpindleSpeed
pool = $pools[[string]$disk.UniqueId]
counter = if ($counter) {
[pscustomobject]@{
temperature = $counter.Temperature
temperature_max = $counter.TemperatureMax
wear = $counter.Wear
power_on_hours = $counter.PowerOnHours
read_errors_uncorrected = $counter.ReadErrorsUncorrected
write_errors_uncorrected = $counter.WriteErrorsUncorrected
}
} else { $null }
}
})
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
counters = $readCounters
disks = $disks
})
"""
_PS_STORAGE_POOLS = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-StoragePool -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
pools = @(Get-StoragePool -IsPrimordial $false | ForEach-Object {
$pool = $_
[pscustomobject]@{
name = [string]$pool.FriendlyName
health = [string]$pool.HealthStatus
operational = @($pool.OperationalStatus | ForEach-Object { [string]$_ })
size = $pool.Size
allocated = $pool.AllocatedSize
resiliency = [string]$pool.ResiliencySettingNameDefault
read_only = [bool]$pool.IsReadOnly
disks = @(Get-PhysicalDisk -StoragePool $pool | ForEach-Object {
[pscustomobject]@{
device_id = [string]$_.DeviceId
unique_id = [string]$_.UniqueId
}
})
}
})
})
"""
_PS_VOLUMES = r"""
$ErrorActionPreference = 'Stop'
if (-not (Get-Command -Name Get-Volume -ErrorAction SilentlyContinue)) {
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ supported = $false })
return
}
$mounts = @{}
try {
foreach ($partition in @(Get-Partition)) {
$paths = @($partition.AccessPaths | Where-Object { $_ })
$folders = @($paths | Where-Object { $_ -notlike '\\?\*' })
foreach ($path in @($paths | Where-Object { $_ -like '\\?\Volume*' })) {
$mounts[$path] = $folders
}
}
} catch { }
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
supported = $true
volumes = @(Get-Volume | Where-Object { [string]$_.DriveType -eq 'Fixed' } | ForEach-Object {
$volume = $_
[pscustomobject]@{
letter = [string]$volume.DriveLetter
label = [string]$volume.FileSystemLabel
file_system = [string]$volume.FileSystem
size = $volume.Size
remaining = $volume.SizeRemaining
health = [string]$volume.HealthStatus
path = [string]$volume.Path
mounts = @($mounts[[string]$volume.Path])
}
})
})
"""
#: ``HealthStatus`` as the contract says it; anything else is "unknown".
_HEALTH = {"healthy": "healthy", "warning": "warning", "unhealthy": "failed"}
#: The same verdict in drive-health terms.
_DRIVE_HEALTH = {"healthy": "ok", "warning": "warning", "unhealthy": "failed"}
_MEDIA = {"hdd": "hdd", "ssd": "ssd", "scm": "ssd"}
_POOL_STATUS = {"healthy": "online", "warning": "degraded", "unhealthy": "faulted"}
_LEVELS = {"simple": "stripe", "mirror": "mirror", "parity": "parity"}
#: Buses of a disk built from other disks, not a drive.
_VIRTUAL_BUSES = frozenset({"spaces", "storage spaces"})
#: ``SpindleSpeed`` when Windows does not know it.
_UNKNOWN_SPEED = 0xFFFFFFFF
def _text(value: Any) -> str:
return str(value or "").strip()
def _number(value: Any) -> int | None:
"""A counter's value; ``None`` when the drive does not report it."""
return None if value is None else int(value)
def _positive(value: Any) -> int | None:
"""A value Windows writes as ``0`` when it has none (a temperature)."""
number = _number(value)
return number if number else None
def _slot(device_id: Any, unique_id: Any) -> str:
"""``PhysicalDisk<N>``, as ``Get-PhysicalDisk`` names a disk; its id when it has no number."""
number = _text(device_id)
return f"PhysicalDisk{number}" if number else _text(unique_id)
class _Disk:
"""One disk of ``_PS_DISKS``."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = raw
self.slot = _slot(raw.get("device_id"), raw.get("unique_id"))
self.counter: dict[str, Any] = raw.get("counter") or {}
self.reports = any(value for value in self.counter.values())
bus = _text(raw.get("bus_type")).lower()
media = _MEDIA.get(_text(raw.get("media_type")).lower(), "unknown")
self.type = "nvme" if bus == "nvme" else media
self.is_physical = bus not in _VIRTUAL_BUSES
self.status = _text(raw.get("health")).lower()
def health(self) -> str:
verdict = _HEALTH.get(self.status, "unknown")
if verdict == "healthy" and self.type == "unknown" and not self.reports:
return "unknown"
return verdict
def disk(self) -> PhysicalDiskDict:
spindle = int(self.raw.get("spindle") or 0)
return {
"slot": self.slot,
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"vendor": _text(self.raw.get("vendor")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"rpm": spindle if spindle != _UNKNOWN_SPEED else 0,
"temperature": _positive(self.counter.get("temperature")) or -1,
"health": self.health(),
"pool": _text(self.raw.get("pool")),
}
def smart(self) -> DiskSmartDict:
c = self.counter
return {
"model": _text(self.raw.get("model") or self.raw.get("name")),
"serial": _text(self.raw.get("serial")),
"type": self.type,
"size": int(self.raw.get("size") or 0),
"health": _DRIVE_HEALTH.get(self.status, "unknown"),
"wearout": None,
"temperature": _positive(c.get("temperature")),
# A spinning disk does not wear out by writes; its Wear is no reading.
"percentage_used": None if self.type == "hdd" else _number(c.get("wear")),
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": _number(c.get("power_on_hours")),
"temperature_max": _positive(c.get("temperature_max")),
"read_errors_uncorrected": _number(c.get("read_errors_uncorrected")),
"write_errors_uncorrected": _number(c.get("write_errors_uncorrected")),
}
def _pool(raw: dict[str, Any]) -> DiskPoolDict:
total, used = int(raw.get("size") or 0), int(raw.get("allocated") or 0)
resiliency = _text(raw.get("resiliency")).lower()
return {
"name": _text(raw.get("name")),
"type": "storage-spaces",
"level": _LEVELS.get(resiliency, resiliency or "unknown"),
"status": _POOL_STATUS.get(_text(raw.get("health")).lower(), "unknown"),
"total": total,
"used": used,
"available": max(total - used, 0),
"disks": [
_slot(d.get("device_id"), d.get("unique_id")) for d in _as_list(raw.get("disks"))
],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
def _mount(raw: dict[str, Any]) -> tuple[str, str] | None:
"""The volume's key and mount point: its drive letter, else the first folder it is
mounted in; None when it is mounted nowhere."""
letter = _text(raw.get("letter")).split("\x00", 1)[0]
if letter:
return f"{letter}:", f"{letter}:\\"
folders = [_text(m) for m in _as_list(raw.get("mounts")) if _text(m)]
if not folders:
return None
return folders[0].rstrip("\\"), folders[0]
def _volume(raw: dict[str, Any], key: str, mountpoint: str) -> HostVolumeDict:
total, available = int(raw.get("size") or 0), int(raw.get("remaining") or 0)
return {
"name": _text(raw.get("label")) or key,
"pool": "",
"type": "filesystem",
"total": total,
"used": max(total - available, 0),
"available": available,
"mountpoint": mountpoint,
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": _text(raw.get("file_system")),
"health": _HEALTH.get(_text(raw.get("health")).lower(), "unknown"),
}
class WindowsStorageMixin(HostStorageMixin):
"""The Storage module's disks, pools, volumes and reliability counters."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _storage_read(self, script: str, what: str) -> dict[str, Any] | None:
"""The script's answer; None when the host has no Storage module.
:raises ValueError: when the reading came back empty -- it could not look.
"""
out = self._run_raw(script).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError(f"the {what} reading came back empty")
return raw if raw.get("supported") else None
def _disks(self) -> list[_Disk]:
raw = self._storage_read(_PS_DISKS, "disk")
if raw is None:
return []
disks = (_Disk(d) for d in _as_list(raw.get("disks")))
return [d for d in disks if d.is_physical]
def get_disks(self) -> list[PhysicalDiskDict]:
"""``Get-PhysicalDisk`` with each disk's temperature; see the module."""
return [d.disk() for d in self._disks()]
def get_disk_smart(self) -> dict[str, DiskSmartDict]:
"""``Get-StorageReliabilityCounter`` per disk; disks that report nothing are left out."""
return {d.slot: d.smart() for d in self._disks() if d.reports}
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
"""Storage Spaces' pools; ``{}`` on a host without any."""
raw = self._storage_read(_PS_STORAGE_POOLS, "storage pool")
pools = [_pool(p) for p in _as_list((raw or {}).get("pools"))]
return {p["name"]: p for p in pools}
def get_volumes(self) -> dict[str, LogicalVolumeDict]:
"""``Get-Volume``'s fixed volumes that are mounted somewhere, keyed by where."""
raw = self._storage_read(_PS_VOLUMES, "volume")
volumes: dict[str, LogicalVolumeDict] = {}
for entry in _as_list((raw or {}).get("volumes")):
mount = _mount(entry)
if mount is not None:
volumes[mount[0]] = _volume(entry, *mount)
return volumes
+85
View File
@@ -0,0 +1,85 @@
"""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")
)
+249
View File
@@ -0,0 +1,249 @@
"""An application's scheduled job as Task Scheduler XML (#8). Pure: no I/O.
:meth:`~napalm_windows.scheduled_tasks.WindowsScheduledJobsMixin.put_scheduled_job`
registers the task this module writes, in the root folder ``\\``, named by the job.
**The cron expression becomes triggers, exactly or not at all.** A day schedule is
one of Task Scheduler's: every day (``ScheduleByDay``), weekdays
(``ScheduleByWeek``), or days of the month in some months (``ScheduleByMonth``).
The times of day become one trigger at the first time with a repetition when they
are three or more evenly spaced (``*/5``, ``*/15 8-17``, ``0 */6``), else one trigger per time,
else one repeating trigger per hour when the minutes are evenly spaced (``*/7``) --
at most 48 triggers, Task Scheduler's limit. ``@reboot`` is a boot trigger. What
Task Scheduler cannot say is refused, naming why: cron's *either* rule (both day
fields set), a weekday together with days of the month or with months, and times
that need more than 48 triggers. A trigger's start is a local time without an
offset, so it follows the host's clock as cron does; a repetition counts elapsed
time, so on the day summer time starts or ends its later runs shift by the hour.
**The command runs in ``cmd.exe``**: ``cmd.exe /d /s /c "<command>"`` -- ``/d``
skips AutoRun, ``/s`` keeps the command as it is between the outer quotes. One line,
as a command line is; the reading gives it back as it was written.
**The principal** is ``SYSTEM`` (the local system account) or a local user, who
runs it whether logged on or not without a stored password (``S4U``): such a run
has no network credentials, so a share needs the computer's access.
**The description** is ``napalm-scheduled-job: <name> <description>`` and a second
line ``schedule: <cron expression>``: the job's name, and its schedule as the
application gave it.
"""
from __future__ import annotations
import html
from itertools import pairwise
from napalm_device_types import ScheduledJobRefused, ScheduledJobSpecDict
from napalm_device_types.cron import CronSchedule, is_reboot, parse_cron
#: The first line of an application's task description, before its name.
JOB_MARKER = "napalm-scheduled-job: "
#: The line of an application's task description that holds its cron expression.
SCHEDULE_LINE = "schedule: "
CMD = "%SystemRoot%\\System32\\cmd.exe"
_CMD_PREFIX = '/d /s /c "'
#: Task Scheduler's limit of triggers on one task.
MAX_TRIGGERS = 48
_START_DATE = "2020-01-01"
_SYSTEM_SID = "S-1-5-18"
_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task"
_WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
_MONTHS = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
_ALL_DAYS = frozenset(range(1, 32))
_ALL_MONTHS = frozenset(range(1, 13))
_ALL_WEEKDAYS = frozenset(range(7))
#: (minute of the day it starts, repetition interval, repetition duration) in minutes.
_Clock = tuple[int, int | None, int | None]
# -- the command ---------------------------------------------------------------------------------
def _escape(text: str) -> str:
"""*text* as XML character data."""
return html.escape(text, quote=False)
def _check_text(what: str, text: str) -> None:
if "\n" in text or "\r" in text:
raise ScheduledJobRefused(f"a task's {what} is one line")
if any(ord(c) < 32 and c != "\t" for c in text):
raise ScheduledJobRefused(f"a task's {what} cannot hold a control character")
def command_action(command: str) -> tuple[str, str]:
"""The ``Exec`` action's command and arguments that run *command* in ``cmd.exe``."""
command = command.strip()
_check_text("command", command)
return CMD, f'{_CMD_PREFIX}{command}"'
def own_command(execute: str | None, arguments: str | None) -> str | None:
"""The command :func:`command_action` wrapped; None for any other action."""
args = arguments or ""
if (execute or "").lower() != CMD.lower():
return None
if not (args.startswith(_CMD_PREFIX) and args.endswith('"') and len(args) > len(_CMD_PREFIX)):
return None
return args[len(_CMD_PREFIX) : -1]
def description(spec: ScheduledJobSpecDict) -> str:
"""The task's description: the job's name and description, then its cron expression."""
first = f"{JOB_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip()
return f"{first}\n{SCHEDULE_LINE}{spec['schedule'].strip()}"
# -- the schedule --------------------------------------------------------------------------------
def _evenly_spaced(values: list[int]) -> int | None:
"""The step between *values*, two or more; None when they are not evenly spaced."""
if len(values) < 2:
return None
step = values[1] - values[0]
return step if all(b - a == step for a, b in pairwise(values)) else None
def _clocks(s: CronSchedule) -> list[_Clock]:
times = sorted(h * 60 + m for h in s.hours for m in s.minutes)
step = _evenly_spaced(times)
if step is not None and len(times) > 2:
return [(times[0], step, times[-1] - times[0] + 1)]
if len(times) <= MAX_TRIGGERS:
return [(t, None, None) for t in times]
minutes = sorted(s.minutes)
step = _evenly_spaced(minutes)
if step is not None and len(s.hours) <= MAX_TRIGGERS:
span = minutes[-1] - minutes[0] + 1
return [(h * 60 + minutes[0], step, span) for h in sorted(s.hours)]
raise ScheduledJobRefused(
f"these times of day need more than {MAX_TRIGGERS} triggers, Task Scheduler's limit"
)
def _names(names: tuple[str, ...], values: frozenset[int], first: int) -> str:
return "".join(f"<{names[v - first]} />" for v in sorted(values))
def _day_schedule(s: CronSchedule) -> str:
if s.either_day:
raise ScheduledJobRefused(
"Task Scheduler cannot fire on either a day of the month or a weekday, "
"as cron does when both are set"
)
every_date = s.days == _ALL_DAYS and s.months == _ALL_MONTHS
if s.weekdays == _ALL_WEEKDAYS and every_date:
return "<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>"
if every_date:
days = _names(_WEEKDAYS, s.weekdays, 0)
return (
f"<ScheduleByWeek><DaysOfWeek>{days}</DaysOfWeek>"
"<WeeksInterval>1</WeeksInterval></ScheduleByWeek>"
)
if s.weekdays == _ALL_WEEKDAYS:
days = "".join(f"<Day>{d}</Day>" for d in sorted(s.days))
months = _names(_MONTHS, s.months, 1)
return (
f"<ScheduleByMonth><DaysOfMonth>{days}</DaysOfMonth>"
f"<Months>{months}</Months></ScheduleByMonth>"
)
raise ScheduledJobRefused(
"Task Scheduler cannot combine a weekday with days of the month or with months"
)
def _duration(minutes: int) -> str:
hours, rest = divmod(minutes, 60)
return "PT" + (f"{hours}H" if hours else "") + (f"{rest}M" if rest or not hours else "")
def _calendar_trigger(clock: _Clock, day_schedule: str) -> str:
start, interval, duration = clock
repetition = ""
if interval is not None and duration is not None:
repetition = (
f"<Repetition><Interval>{_duration(interval)}</Interval>"
f"<Duration>{_duration(duration)}</Duration>"
"<StopAtDurationEnd>false</StopAtDurationEnd></Repetition>"
)
hour, minute = divmod(start, 60)
return (
f"<CalendarTrigger>{repetition}"
f"<StartBoundary>{_START_DATE}T{hour:02d}:{minute:02d}:00</StartBoundary>"
f"<Enabled>true</Enabled>{day_schedule}</CalendarTrigger>"
)
def triggers(schedule: str) -> list[str]:
"""The triggers that fire exactly when the cron expression *schedule* does.
:raises ScheduledJobRefused: for a shape Task Scheduler cannot express, or an
expression cron would not take.
"""
if is_reboot(schedule):
return ["<BootTrigger><Enabled>true</Enabled></BootTrigger>"]
try:
s = parse_cron(schedule)
except ValueError as exc:
raise ScheduledJobRefused(str(exc)) from exc
day_schedule = _day_schedule(s)
return [_calendar_trigger(clock, day_schedule) for clock in _clocks(s)]
# -- the task ------------------------------------------------------------------------------------
def _principal(run_as: str) -> str:
if run_as.upper() == "SYSTEM":
return f"<UserId>{_SYSTEM_SID}</UserId><RunLevel>HighestAvailable</RunLevel>"
return (
f"<UserId>{_escape(run_as)}</UserId><LogonType>S4U</LogonType>"
"<RunLevel>LeastPrivilege</RunLevel>"
)
def task_xml(spec: ScheduledJobSpecDict) -> str:
"""The whole task for *spec*, as ``Register-ScheduledTask -Xml`` takes it.
:raises ScheduledJobRefused: for a schedule, command or description a task
cannot hold.
"""
execute, arguments = command_action(spec["command"])
_check_text("description", spec.get("description") or "")
trigger_xml = "".join(triggers(spec["schedule"]))
enabled = "true" if spec["enabled"] else "false"
return (
f'<Task version="1.2" xmlns="{_NAMESPACE}">'
f"<RegistrationInfo><Description>{_escape(description(spec))}</Description>"
"</RegistrationInfo>"
f"<Triggers>{trigger_xml}</Triggers>"
f'<Principals><Principal id="Author">{_principal(spec["run_as"])}</Principal></Principals>'
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>"
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"
"<StartWhenAvailable>false</StartWhenAvailable>"
"<AllowStartOnDemand>true</AllowStartOnDemand>"
f"<Enabled>{enabled}</Enabled></Settings>"
f'<Actions Context="Author"><Exec><Command>{_escape(execute)}</Command>'
f"<Arguments>{_escape(arguments)}</Arguments></Exec></Actions>"
"</Task>"
)
+221
View File
@@ -0,0 +1,221 @@
"""Time sync on Windows: the Windows Time service (w32time) and the time zone (NetOrk/netork#2367).
:class:`WindowsTimeSyncMixin` implements napalm-device-types'
:class:`~napalm_device_types.time_sync.TimeSyncMixin` for the driver, which carries
each script across ``PsrpTransport.run``.
**Reading** is one script. The servers and the mode are w32time's registry values
(``Type``, ``NtpServer``), where group policy's override the local ones -- the
registry, not ``w32tm /query /configuration``, whose text is in the host's language.
``NtpServer`` lists ``name,0xFLAGS`` pairs; the flags are dropped. ``Type NoSync``
takes time from nowhere: no servers. Synchronised is the leap indicator of
``w32tm /query /status`` (``3`` = not synchronised), the one value on the first line
whatever the language; a stopped service is not synchronised. The zone is what
``tzutil /g`` reads, the registry's ``TimeZoneInformation`` (``TimeZoneKeyName``), as an
IANA name (:mod:`napalm_windows.time_zones`); one with summer time switched off
(``DynamicDaylightTimeDisabled``, tzutil's ``_dstoff``) is not that zone, and reads as
None. The registry is read anew each time, where ``[TimeZoneInfo]::Local`` is cached
for the life of the remote session.
**Writing the servers** is what ``w32tm /config /manualpeerlist:"a,0x8 b,0x8"
/syncfromflags:manual`` writes -- ``NtpServer`` (``0x8``: client mode, which public
servers answer) and ``Type NTP`` -- set with ``Set-ItemProperty``, then
``w32tm /config /update``, after starting the service where it is stopped. No value
goes through a native command line, whose quoting Windows PowerShell 5.1 mangles.
Two kinds of host are refused before anything is written: a domain member that takes
its time from the domain hierarchy (``NT5DS``, ``AllSync``) -- the domain sets its
time, not the host -- and a host whose w32time settings come from group policy, which
would override the write.
**Writing the zone** is ``Set-TimeZone -Id`` (``tzutil /s``), which also switches summer
time back on. Windows keeps a Windows zone, which stands for
several IANA zones; the IANA name written is kept beside it
(``HKLM:\\SOFTWARE\\napalm-windows``, ``IanaTimeZone``) and read back while the
host is still in its Windows zone, so the zone reads back as written. A zone changed
by hand since reads as its CLDR name.
Each write is skipped where the host already has what it would write.
"""
from __future__ import annotations
import json
import re
from typing import TYPE_CHECKING, Any, ClassVar
from napalm_device_types.models import FixStepOutcomeDict
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
from napalm_windows._powershell import _ps_quote
from napalm_windows.time_zones import IANA_TO_WINDOWS, iana_time_zone, windows_time_zone
_W32TIME = r"HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters"
_TZ_INFO = r"HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\W32Time\Parameters"
#: Where the IANA name of the zone written is kept.
MARKER_KEY = r"HKLM:\SOFTWARE\napalm-windows"
#: w32time's modes that take time from the domain hierarchy.
_DOMAIN_TYPES = frozenset({"nt5ds", "allsync"})
# w32tm runs inside cmd.exe with its stderr merged: in a remote session a line on
# stderr would be an error record, and the whole reading would fail.
_PS_TIME_SYNC = rf"""
$ErrorActionPreference = 'Stop'
function V($path, $name) {{
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
if ($item) {{ [string]$item.$name }}
}}
$svc = Get-Service -Name W32Time -ErrorAction SilentlyContinue
$status = $null
if ($svc -and [string]$svc.Status -eq 'Running') {{
$status = @(cmd.exe /c 'w32tm /query /status 2>&1') -join "`n"
}}
[pscustomobject]@{{
type = V '{_W32TIME}' 'Type'
ntp_server = V '{_W32TIME}' 'NtpServer'
policy_type = V '{_POLICY}' 'Type'
policy_server = V '{_POLICY}' 'NtpServer'
service = if ($svc) {{ [string]$svc.Status }} else {{ $null }}
status = $status
zone = V '{_TZ_INFO}' 'TimeZoneKeyName'
dst_off = V '{_TZ_INFO}' 'DynamicDaylightTimeDisabled'
iana_zone = V '{MARKER_KEY}' 'IanaTimeZone'
}} | ConvertTo-Json -Compress
"""
_PS_SET_SERVERS = f"""
$ErrorActionPreference = 'Stop'
Set-ItemProperty -Path '{_W32TIME}' -Name NtpServer -Value {{peers}}
Set-ItemProperty -Path '{_W32TIME}' -Name Type -Value 'NTP'
if ([string](Get-Service -Name W32Time).Status -ne 'Running') {{{{ Start-Service -Name W32Time }}}}
$out = @(cmd.exe /c 'w32tm /config /update 2>&1')
if ($LASTEXITCODE -ne 0) {{{{ throw ('w32tm /config /update: ' + ($out -join ' ')) }}}}
"""
_PS_SET_ZONE = """
$ErrorActionPreference = 'Stop'
Set-TimeZone -Id {windows}
"""
_PS_MARK_ZONE = """
if (-not (Test-Path -Path '{key}')) {{ New-Item -Path '{key}' | Out-Null }}
Set-ItemProperty -Path '{key}' -Name IanaTimeZone -Value {zone}
"""
_LEAP = re.compile(r":\s*([0-3])\b")
def _servers(value: str | None) -> list[str]:
"""``NtpServer``'s names in order, without their ``,0xFLAGS``, each once."""
names: list[str] = []
for entry in (value or "").split():
name = entry.split(",", 1)[0].strip()
if name and name.lower() not in (n.lower() for n in names):
names.append(name)
return names
def _synchronized(service: str | None, status: str | None) -> bool | None:
"""The leap indicator, the first line of ``w32tm /query /status``: 3 is unsynchronised."""
if service is None:
return None
if service.lower() != "running":
return False
first = (status or "").strip().splitlines()[:1]
match = _LEAP.search(first[0]) if first else None
return None if match is None else match.group(1) != "3"
def _windows_zone(raw: dict[str, Any]) -> str:
"""``TimeZoneKeyName``, which older Windows pad with NULs."""
return str(raw.get("zone") or "").split("\x00", 1)[0].strip()
def _time_zone(raw: dict[str, Any]) -> str | None:
"""The host's zone as an IANA name: the one written while the host keeps its Windows
zone, else CLDR's; None for summer time switched off or a zone not in the table."""
windows, marker = _windows_zone(raw), str(raw.get("iana_zone") or "")
if not windows or str(raw.get("dst_off") or "0").strip() != "0":
return None
if marker and IANA_TO_WINDOWS.get(marker) == windows:
return marker
return iana_time_zone(windows)
class _Reading:
"""What the reading script said, with group policy applied."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = raw
self.by_policy = bool(raw.get("policy_type") or raw.get("policy_server"))
self.type = str(raw.get("policy_type") or raw.get("type") or "").strip().lower()
self.servers = _servers(raw.get("policy_server") or raw.get("ntp_server"))
def time_sync(self) -> TimeSyncDict:
return {
"ntp_servers": [] if self.type == "nosync" else self.servers,
"timezone": _time_zone(self.raw),
"synchronized": _synchronized(self.raw.get("service"), self.raw.get("status")),
"daemon": "w32time",
}
class WindowsTimeSyncMixin(TimeSyncMixin):
"""w32time's servers and the time zone; the driver carries the scripts."""
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def _ts_read(self) -> _Reading:
out = self._run_raw(_PS_TIME_SYNC).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the time sync reading came back empty")
return _Reading(raw)
def get_time_sync(self) -> TimeSyncDict:
"""w32time's servers, whether it is synchronised, and the zone; one round trip.
:raises ValueError: when the reading came back empty.
"""
return self._ts_read().time_sync()
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
"""``w32tm /config`` with *servers* as manual peers; see the module."""
now = self._ts_read()
if now.by_policy:
return {
"ok": False,
"output": "the Windows Time settings come from group policy; "
"they are changed there, not on the host",
}
if now.type in _DOMAIN_TYPES:
return {
"ok": False,
"output": "the host takes its time from the domain hierarchy "
f"(w32time Type {now.raw.get('type')}); the domain sets its time sources",
}
if now.type == "ntp" and [s.lower() for s in now.servers] == [s.lower() for s in servers]:
return {"ok": True, "output": "w32time already has these servers"}
peers = " ".join(f"{server},0x8" for server in servers)
self._run_raw(_PS_SET_SERVERS.format(peers=_ps_quote(peers)))
return {"ok": True, "output": f"w32time set to {', '.join(servers)}"}
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
"""``Set-TimeZone`` to *zone*'s Windows zone, and *zone* kept beside it; see the module."""
windows = windows_time_zone(zone)
if windows is None:
return {"ok": False, "output": f"there is no Windows time zone for {zone}"}
now = self._ts_read().raw
script = ""
if _windows_zone(now) != windows or str(now.get("dst_off") or "0").strip() != "0":
script += _PS_SET_ZONE.format(windows=_ps_quote(windows))
if script or now.get("iana_zone") != zone:
script += _PS_MARK_ZONE.format(key=MARKER_KEY, zone=_ps_quote(zone))
if not script:
return {"ok": True, "output": f"the host is in {zone} already"}
self._run_raw(script)
return {"ok": True, "output": f"time zone set to {windows} ({zone})"}
+31
View File
@@ -0,0 +1,31 @@
"""Windows time zone ids and IANA names, both ways.
Windows names its zones by their standard-time name (``W. Europe Standard Time``);
the contracts want an IANA name. The tables are CLDR's ``windowsZones.xml``,
generated into :mod:`napalm_windows._windows_zones` by ``tools/windows_zones.py``
and never fetched at runtime:
* reading, a Windows zone is the zone CLDR names for its territory ``001`` -- one
of several a Windows zone stands for (``W. Europe Standard Time`` is Berlin,
Vienna, Rome, ...). A zone not in the table is ``None``: the reading says it does
not know rather than guess;
* writing, every IANA name CLDR maps, and the tzdata links to and from them, has
its Windows zone.
"""
from __future__ import annotations
from napalm_windows._windows_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA
def iana_time_zone(windows_id: str | None) -> str | None:
"""The IANA name of the Windows zone *windows_id*; None for one the table lacks."""
return WINDOWS_TO_IANA.get(windows_id or "")
def windows_time_zone(iana: str | None) -> str | None:
"""The Windows zone that keeps the IANA zone *iana*; None for one Windows lacks."""
return IANA_TO_WINDOWS.get(iana or "")
__all__ = ["IANA_TO_WINDOWS", "WINDOWS_TO_IANA", "iana_time_zone", "windows_time_zone"]
+66
View File
@@ -10,15 +10,22 @@ transport (Windows OpenSSH) would implement later.
from __future__ import annotations
import logging
import time
from collections.abc import Callable
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.complex_objects import PSInvocationState
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
logger = logging.getLogger(__name__)
#: The longest one poll of a streaming script waits for output, so its limit is
#: checked at least this often.
_POLL_SECONDS = 20
class PowerShellError(Exception):
"""A script ran but wrote to PowerShell's error stream."""
@@ -104,6 +111,65 @@ class PsrpTransport:
raise PowerShellError(message or "PowerShell reported an error")
return "\n".join(str(o) for o in output if o is not None)
def run_streaming(
self, script: str, on_output: Callable[[str], None], *, limit: float
) -> list[str]:
"""Run a long script, handing each output object to *on_output* as it arrives.
For a run that takes minutes: the pipeline is started and polled, each poll
waiting at most ``_POLL_SECONDS`` (and less than a read of the connection), so
output reaches the caller while the host still works. A script still running
after *limit* seconds is stopped (Ctrl+C to the pipeline) and raises
:class:`TimeoutError`. An error the script wrote raises :class:`PowerShellError`
once it ended, after its output was passed on.
:returns: Every output object, as text, in order.
"""
if self._pool is None:
raise ConnectionClosedException("WinRM connection is not open")
ps = PowerShell(self._pool)
ps.add_script(script)
poll = min(_POLL_SECONDS, max(self.timeout // 2, 1))
deadline = time.monotonic() + limit
taken, out = 0, []
ps.begin_invoke()
while ps.state == PSInvocationState.RUNNING:
if time.monotonic() > deadline:
self._stop(ps)
raise TimeoutError(f"The script did not end within {int(limit)} seconds")
ps.poll_invoke(timeout=poll)
arrived, taken = ps.output[taken:], len(ps.output)
for item in arrived:
if item is not None:
out.append(str(item))
on_output(out[-1])
if ps.had_errors:
message = "; ".join(str(e) for e in ps.streams.error).strip()
raise PowerShellError(message or "PowerShell reported an error")
return out
def _stop(self, ps: PowerShell) -> None:
try:
ps.stop()
except Exception: # a pipeline that ended meanwhile has nothing to stop
logger.debug("Stopping a pipeline on %s failed", self.host, exc_info=True)
def run_last(self, script: str) -> bool:
"""Run a script after which the host may stop answering: a restart, a shutdown.
True when the script finished. False when the connection broke before the
answer came, which for such a script means the host went down first; the
transport is closed then. An error the script wrote still raises
:class:`PowerShellError`: the host answered, and refused.
"""
try:
self.run(script)
except (requests.RequestException, WinRMError, OSError) as exc:
logger.debug("Connection to %s broke during its last script: %s", self.host, exc)
self._drop()
return False
return True
def close(self) -> None:
if self._pool is not None:
try:
+71 -51
View File
@@ -24,9 +24,23 @@ from typing import Any
from napalm.base.exceptions import ConnectionClosedException
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.event_channels import WindowsLogSourcesMixin
from napalm_windows.host_basics import WindowsHostBasicsMixin
from napalm_windows.host_events import WindowsHostEventsMixin
from napalm_windows.host_firewall import WindowsHostFirewallMixin
from napalm_windows.logins import WindowsLoginsMixin
from napalm_windows.posture import WindowsPostureMixin
from napalm_windows.repairs import WindowsRepairsMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.services import WindowsServicesMixin
from napalm_windows.storage import WindowsStorageMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
from napalm_windows.windows_features import WindowsFeaturesMixin
from napalm_windows.windows_update import WindowsUpdateMixin
logger = logging.getLogger(__name__)
@@ -120,20 +134,6 @@ ConvertTo-Json -Compress -Depth 3 -InputObject @(
)
"""
_PS_SERVICES = r"""
$ErrorActionPreference = 'Stop'
ConvertTo-Json -Compress -Depth 3 -InputObject @(
Get-CimInstance -ClassName Win32_Service | ForEach-Object {
[pscustomobject]@{
name = $_.Name
state = [string]$_.State
start_mode = [string]$_.StartMode
pid = [int]$_.ProcessId
}
}
)
"""
# Every listening TCP and bound UDP socket, the processes holding them and the
# services those processes run. Sockets owned by http.sys (WinRM, IIS) belong to
# the System process; a shared svchost runs several services in one process.
@@ -178,13 +178,16 @@ _SERVICE_COMMANDS = {
"disable": "Set-Service -Name {name} -StartupType Disabled",
}
# The host's own restart and shutdown, without -Force: Windows asks running programs to
# close and refuses while other users are logged on, instead of throwing away what they
# have not saved. Both start the shutdown and return; WinRM goes later, with the services.
_PS_REBOOT = "Restart-Computer -Confirm:$false -ErrorAction Stop"
_PS_SHUTDOWN = "Stop-Computer -Confirm:$false -ErrorAction Stop"
# Service key names, not display names: letters, digits and the few symbols
# real services use (MSSQL$SQLEXPRESS, CDPUserSvc_4a5b6, {GUID}-style names).
_SERVICE_NAME_RE = re.compile(r"^[\w.$@{}\-]+$", re.ASCII)
# PowerShell accepts these as single-quote delimiters alongside the ASCII one.
_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛")
_ROUTE_PROTOCOLS = {
"local": "connected",
"routeradvertisement": "connected",
@@ -195,7 +198,6 @@ _ROUTE_PROTOCOLS = {
"rip": "rip",
}
_ENABLED_START_MODES = {"auto", "boot", "system"}
_DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
@@ -204,22 +206,6 @@ _DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"}
# ---------------------------------------------------------------------------
def _as_list(value: Any) -> list[Any]:
"""Undo ConvertTo-Json unwrapping a one-element array into a bare value."""
if value is None:
return []
if isinstance(value, list):
return value
return [value]
def _ps_quote(value: str) -> str:
"""Quote ``value`` as a PowerShell single-quoted (verbatim) string."""
for q in _PS_SINGLE_QUOTES:
value = value.replace(q, q + q)
return f"'{value}'"
def _mac(value: str | None) -> str:
"""``00-15-5d-01-02-03`` → ``00:15:5D:01:02:03``."""
if not value:
@@ -271,7 +257,22 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(OSDriver):
class WindowsDriver(
WindowsScheduledJobsMixin,
WindowsTimeSyncMixin,
WindowsStorageMixin,
WindowsHostBasicsMixin,
WindowsLoginsMixin,
WindowsHostFirewallMixin,
WindowsFeaturesMixin,
WindowsServicesMixin,
WindowsHostEventsMixin,
WindowsLogSourcesMixin,
WindowsRepairsMixin,
WindowsUpdateMixin,
WindowsPostureMixin,
OSDriver,
):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
@@ -369,6 +370,15 @@ class WindowsDriver(OSDriver):
raise ConnectionClosedException("WinRM connection is not open")
return self._transport.run(script)
def _run_power(self, script: str, what: str) -> None:
"""Send a restart or shutdown; the connection the host drops counts as accepted."""
if self._transport is None:
raise ConnectionClosedException("WinRM connection is not open")
try:
self._transport.run_last(script)
except PowerShellError as exc:
raise RuntimeError(f"The host refused to {what}: {exc}") from exc
# ------------------------------------------------------------------
# NAPALM getters
# ------------------------------------------------------------------
@@ -436,6 +446,8 @@ class WindowsDriver(OSDriver):
return result
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
"""Get-NetNeighbor's IPv4 neighbours. It reports a state but no age, so
``age`` is ``-1.0`` (unknown, napalm-device-types' ``ARP_AGE_UNKNOWN``)."""
entries = []
for n in _as_list(self._run_ps(_PS_ARP)):
if (n.get("state") or "").lower() in _DEAD_NEIGHBOUR_STATES:
@@ -443,7 +455,7 @@ class WindowsDriver(OSDriver):
mac = _mac(n.get("mac"))
if not _is_real_neighbour_mac(mac):
continue
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": 0.0})
entries.append({"interface": n["interface"], "mac": mac, "ip": n["ip"], "age": -1.0})
return entries
def get_route_to(
@@ -488,20 +500,6 @@ class WindowsDriver(OSDriver):
# Services
# ------------------------------------------------------------------
def get_services(self) -> list[ServiceDict]:
services: list[ServiceDict] = []
for s in _as_list(self._run_ps(_PS_SERVICES)):
running = (s.get("state") or "").lower() == "running"
services.append(
{
"name": s["name"],
"running": running,
"enabled": (s.get("start_mode") or "").lower() in _ENABLED_START_MODES,
"pid": int(s.get("pid") or 0) if running else 0,
}
)
return services
def get_listening_sockets(self) -> ListeningSocketsDict:
"""Every listening TCP and bound UDP socket, with the process and the
Windows service behind it (``Get-NetTCPConnection``, ``Get-NetUDPEndpoint``,
@@ -520,6 +518,28 @@ class WindowsDriver(OSDriver):
sockets.sort(key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or ""))
return {"attributed": True, "sockets": sockets}
def reboot_host(self) -> None:
"""Restart the host cleanly (``HostRebootMixin``) with ``Restart-Computer``.
Not forced: programs are asked to close, and Windows refuses while other users
are logged on, a disconnected session included. Returns once the restart is
under way; a connection the host drops before answering counts as that.
:raises RuntimeError: when the host refuses, with its answer.
"""
self._run_power(_PS_REBOOT, "restart")
def shutdown_host(self) -> None:
"""Shut the host down cleanly and power it off (``HostShutdownMixin``) with
``Stop-Computer``.
Not forced, as :meth:`reboot_host`. Returns once the shutdown is under way; a
connection the host drops before answering counts as that.
:raises RuntimeError: when the host refuses, with its answer.
"""
self._run_power(_PS_SHUTDOWN, "shut down")
def manage_service(self, name: str, action: str) -> dict[str, Any]:
template = _SERVICE_COMMANDS.get(action)
if template is None:
+71
View File
@@ -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)
+445
View File
@@ -0,0 +1,445 @@
"""Windows Update over PowerShell Remoting: search, pending updates, history (netork#2892).
:class:`WindowsUpdateMixin` implements napalm-device-types'
:class:`~napalm_device_types.updates.UpdateMixin` for the driver with the Windows Update
Agent's COM API (``Microsoft.Update.Session``).
**The search is the refresh.** ``refresh_available_updates`` searches the source the
host is configured for (Windows Update, or its WSUS server) for what is not installed
and not hidden, software only -- no drivers. A search takes minutes, so the poll never
runs one: the search keeps its reading in the registry (:data:`STORE`, under
``HKLM\\SOFTWARE``, where only administrators and SYSTEM may write), and
``get_available_updates`` reads it back, leaving out what the host's own history shows
installed since. Before the first search there is nothing to read from, which is
napalm-device-types' :exc:`PackageIndexMissing`: a refresh cures it.
**An update is named by what it keeps from month to month** (:func:`update_name`): its
title without the month, the KB article and the version. Next month's cumulative update
takes this one's place under the same name, so "pending since" is not reset every
month. The KB articles are the update's ``new_version`` and ``advisories``; its
``CveIDs`` and ``MsrcSeverity`` go along as ``cves`` and ``vendor_severity``. A security
update, a definition update or one naming CVEs is ``security``. Optional updates
(previews Windows does not install by itself) and feature upgrades are not pending:
this path installs neither.
**The history** is ``QueryHistory``, its newest 300 entries, one transaction each;
``requested_by`` is the ``ClientApplicationID`` that asked (``UpdateOrchestrator``,
``AutomaticUpdates``, ``napalm-windows`` for the driver's own runs).
**Installing** is :mod:`napalm_windows.windows_update_run`: Windows refuses a download
or an install over a network logon, so it runs in a one-shot SYSTEM task.
"""
from __future__ import annotations
import json
import re
import unicodedata
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_device_types import PackageIndexMissing
from napalm_device_types.models import ApplyUpdatesResultDict, UpdateDict
from napalm_device_types.updates import UpdateHistoryDict, UpdateHistoryPackageDict, UpdateMixin
from napalm_windows._powershell import _as_list
from napalm_windows.transport import PowerShellError
from napalm_windows.windows_update_run import install
#: Where the search keeps its reading, and the runs theirs.
STORE = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate"
#: What every search asks: not installed, not hidden, no drivers.
_CRITERIA = "IsInstalled=0 and IsHidden=0 and Type='Software'"
# The search, kept in STORE for the poll, and printed for the refresh. Its times are
# unix seconds; the WSUS server is named where group policy points the host at one.
_PS_WU_SEARCH = r"""
$ErrorActionPreference = 'Stop'
$started = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'napalm-windows'
$found = $session.CreateUpdateSearcher().Search("__CRITERIA__")
$rows = @(foreach ($u in $found.Updates) {
[pscustomobject]@{
id = [string]$u.Identity.UpdateID
revision = [int]$u.Identity.RevisionNumber
title = [string]$u.Title
kb = @(foreach ($k in $u.KBArticleIDs) { [string]$k })
cves = @(foreach ($c in $u.CveIDs) { [string]$c })
severity = [string]$u.MsrcSeverity
classifications = @(foreach ($c in $u.Categories) {
if ([string]$c.Type -eq 'UpdateClassification') { [string]$c.CategoryID }
})
browse_only = [bool]$u.BrowseOnly
interactive = [bool]$u.InstallationBehavior.CanRequestUserInput
reboot = [int]$u.InstallationBehavior.RebootBehavior
eula_accepted = [bool]$u.EulaAccepted
downloaded = [bool]$u.IsDownloaded
}
})
$policy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate'
$wsus = $null
if ((Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath "$policy\AU").UseWUServer -eq 1) {
$wsus = [string](Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath $policy).WUServer
}
$reading = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
searched_at = $started
finished_at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
result = [int]$found.ResultCode
wsus = $wsus
updates = $rows
})
$store = '__STORE__'
if (-not (Test-Path -LiteralPath $store)) { New-Item -Path $store -Force | Out-Null }
Set-ItemProperty -LiteralPath $store -Name Search -Value $reading
$reading
""".replace("__CRITERIA__", _CRITERIA).replace("__STORE__", STORE)
# What the last search found, and what the host installed (by its history) -- no search.
_PS_WU_PENDING = r"""
$ErrorActionPreference = 'Stop'
$search = (Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath '__STORE__').Search
$installed = @()
$history_error = $null
if ($search) {
try {
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
$count = $searcher.GetTotalHistoryCount()
if ($count -gt 0) {
$installed = @(foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
if ($h.Operation -eq 1 -and ($h.ResultCode -eq 2 -or $h.ResultCode -eq 3)) {
[pscustomobject]@{
id = [string]$h.UpdateIdentity.UpdateID
revision = [int]$h.UpdateIdentity.RevisionNumber
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
}
}
})
}
} catch {
$history_error = $_.Exception.Message
}
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
search = $search
installed = $installed
history_error = $history_error
})
""".replace("__STORE__", STORE)
# The newest 300 entries of the host's update history; times are UTC, as unix seconds.
_PS_WU_HISTORY = r"""
$ErrorActionPreference = 'Stop'
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
$count = $searcher.GetTotalHistoryCount()
ConvertTo-Json -Compress -Depth 3 -InputObject @(if ($count -gt 0) {
foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
[pscustomobject]@{
id = [string]$h.UpdateIdentity.UpdateID
revision = [int]$h.UpdateIdentity.RevisionNumber
title = [string]$h.Title
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
operation = [int]$h.Operation
result = [int]$h.ResultCode
hresult = [int64]$h.HResult
client = [string]$h.ClientApplicationID
}
}
})
"""
#: The update classifications (``ICategory.CategoryID``, the same in every language).
_SECURITY_UPDATES = "0fa1201d-4330-4fa8-8ae9-b877473b6441"
_DEFINITION_UPDATES = "e0789628-ce08-4437-be74-2495b842f43b"
_UPGRADES = "3689bdc8-b205-4af4-8d4a-a63924c5e9d5"
#: napalm-device-types' package name rule (``UpdateMixin.apply_updates``).
NAME = re.compile(r"[a-zA-Z0-9_\-+.]+")
#: Short enough for a store that keeps a package name in 255 characters.
NAME_MAX = 200
_DATE_PREFIX = re.compile(r"^\s*\d{4}-\d{2}\s+")
_VERSIONED = re.compile(r"\([^()]*\d+\.\d+[^()]*\)") # "(Version 1.441.120.0)", "(26100.2894)"
_KB = re.compile(r"\(?\bKB\d+\b\)?", re.IGNORECASE)
_V_SUFFIX = re.compile(r"\s+-?\s*v\d+(?:\.\d+)+", re.IGNORECASE) # "- v5.141"
_NOT_NAME = re.compile(r"[^A-Za-z0-9._+-]+")
_DASHES = re.compile(r"-{2,}")
_KB_IN_TITLE = re.compile(r"\bKB(\d+)\b", re.IGNORECASE)
#: MsrcSeverity, lowest first.
_SEVERITIES = ("Low", "Moderate", "Important", "Critical")
#: IUpdateHistoryEntry.ResultCode: what a finished entry other than success says.
_RESULTS = {3: "succeeded with errors", 4: "failed", 5: "aborted"}
_IN_PROGRESS = 1
_UNINSTALL = 2
def update_name(title: str, kbs: list[str], update_id: str) -> str:
"""The name of an update: its title without month, KB article and version, as a
package name (:data:`NAME`); its KB article or its ID when nothing is left."""
text = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode()
for pattern in (_DATE_PREFIX, _VERSIONED, _KB, _V_SUFFIX):
text = pattern.sub(" ", text)
name = _DASHES.sub("-", _NOT_NAME.sub("-", text)).strip("-.")
name = name[:NAME_MAX].rstrip("-.")
if name:
return name
return f"KB{kbs[0]}" if kbs else update_id
class Offer(NamedTuple):
"""One update the search offers: its exact identity and what it is."""
identity: str # "<UpdateID>:<RevisionNumber>"
name: str
title: str
advisories: list[str]
cves: list[str]
severity: str | None
security: bool | None
def _security(classifications: list[str], cves: list[str], severity: str | None) -> bool | None:
if cves or severity or {_SECURITY_UPDATES, _DEFINITION_UPDATES} & set(classifications):
return True
return False if classifications else None
def _strings(value: Any) -> list[str]:
return [str(v) for v in _as_list(value)]
def _text(value: Any) -> str | None:
"""A string the host may have left empty or out; None then."""
return str(value or "") or None
def _identity(entry: dict[str, Any]) -> str:
return f"{entry['id']}:{int(entry.get('revision') or 0)}"
def _offer(update: dict[str, Any]) -> Offer | None:
"""The offer *update* is; None for one this path does not install."""
classifications = [c.lower() for c in _strings(update.get("classifications"))]
if update.get("browse_only") or _UPGRADES in classifications:
return None
kbs, cves = _strings(update.get("kb")), _strings(update.get("cves"))
severity = _text(update.get("severity"))
title = str(update.get("title") or "")
return Offer(
identity=_identity(update),
name=update_name(title, kbs, str(update["id"])),
title=title,
advisories=[f"KB{k}" for k in kbs],
cves=cves,
severity=severity,
security=_security(classifications, cves, severity),
)
class Search(NamedTuple):
"""What one search found."""
searched_at: int
seconds: int
origin: str
offers: list[Offer]
def parse_search(raw: Any) -> Search:
"""The search :data:`_PS_WU_SEARCH` printed, or kept.
:raises ValueError: when *raw* is no search.
"""
if not isinstance(raw, dict) or "updates" not in raw:
raise ValueError("not a Windows Update search")
started = int(raw.get("searched_at") or 0)
wsus = raw.get("wsus")
offers = [o for u in _as_list(raw["updates"]) if (o := _offer(u)) is not None]
return Search(
searched_at=started,
seconds=max(int(raw.get("finished_at") or started) - started, 0),
origin=f"WSUS {wsus}" if wsus else "Windows Update",
offers=offers,
)
def _higher(first: str | None, second: str | None) -> str | None:
def rank(s: str | None) -> int:
return _SEVERITIES.index(s) if s in _SEVERITIES else -1
return first if rank(first) >= rank(second) else second
def _merged(into: UpdateDict, offer: Offer) -> None:
into["advisories"] = [*into.get("advisories", []), *offer.advisories]
into["new_version"] = " ".join(into["advisories"]) or into["new_version"]
into["cves"] = [*into.get("cves", []), *(c for c in offer.cves if c not in into["cves"])]
into["vendor_severity"] = _higher(into.get("vendor_severity"), offer.severity)
first, second = into.get("security"), offer.security
if first or second:
into["security"] = True
elif first is None or second is None:
into["security"] = None
def pending_updates(search: Search) -> list[UpdateDict]:
"""One update per name: offers of the same name are one, their KBs and CVEs together."""
by_name: dict[str, UpdateDict] = {}
for offer in search.offers:
if offer.name in by_name:
_merged(by_name[offer.name], offer)
continue
by_name[offer.name] = {
"name": offer.name,
"current_version": "",
"new_version": " ".join(offer.advisories) or f"rev {offer.identity.split(':')[-1]}",
"origin": search.origin,
"security": offer.security,
"title": offer.title,
"advisories": list(offer.advisories),
"cves": list(offer.cves),
"vendor_severity": offer.severity,
}
return list(by_name.values())
def _installed_since(reading: dict[str, Any], since: int) -> set[str]:
return {
_identity(h) for h in _as_list(reading.get("installed")) if int(h.get("at") or 0) >= since
}
def parse_pending(output: str) -> Search:
"""The last search :data:`_PS_WU_PENDING` printed, without what was installed since.
:raises PackageIndexMissing: before the first search.
:raises ValueError: when the kept reading is no search.
"""
reading = json.loads(output) if output.strip() else {}
if not reading.get("search"):
raise PackageIndexMissing("Windows Update has not been searched yet; a refresh searches it")
search = parse_search(json.loads(reading["search"]))
done = _installed_since(reading, search.searched_at)
return search._replace(offers=[o for o in search.offers if o.identity not in done])
def _hresult(value: Any) -> str:
return f"0x{int(value or 0) & 0xFFFFFFFF:08X}"
def _error(entry: dict[str, Any]) -> str | None:
word = _RESULTS.get(int(entry.get("result") or 0))
if word is None:
return None
return f"{word} ({_hresult(entry['hresult'])})" if entry.get("hresult") else word
def _package(title: str, update_id: str, removed: bool) -> UpdateHistoryPackageDict:
"""What one history entry changed; the history names no KB but in the title."""
kb = [m.upper() for m in _KB_IN_TITLE.findall(title)]
version = f"KB{kb[0]}" if kb else None
return {
"name": update_name(title, kb, update_id),
"action": "remove" if removed else "install",
"old_version": version if removed else None,
"new_version": None if removed else version,
"title": title,
}
def _transaction(entry: dict[str, Any]) -> UpdateHistoryDict:
operation = int(entry.get("operation") or 1)
at = int(entry["at"])
title = str(entry.get("title") or "")
return {
"id": f"{_identity(entry)}:{operation}:{at}",
"start": at,
"end": None if int(entry.get("result") or 0) == _IN_PROGRESS else at,
"packages": [_package(title, str(entry["id"]), operation == _UNINSTALL)],
"requested_by": _text(entry.get("client")),
"command": None,
"error": _error(entry),
}
def parse_history(output: str, since: int | None) -> list[UpdateHistoryDict]:
"""The transactions :data:`_PS_WU_HISTORY` printed that started at or after *since*,
newest first."""
entries = _as_list(json.loads(output)) if output.strip() else []
found = [_transaction(e) for e in entries if since is None or int(e["at"]) >= since]
return sorted(found, key=lambda t: t["start"], reverse=True)
# ---------------------------------------------------------------------------
# The mixin
# ---------------------------------------------------------------------------
class WindowsUpdateMixin(UpdateMixin):
"""Windows Update as napalm-device-types' updates; the driver carries the scripts."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def refresh_available_updates(self) -> dict[str, Any]:
"""Search the host's update source, and keep what it found for the poll.
A search takes minutes. One that Windows refuses (no connection to the source)
is a failed refresh, and the reading from the last search stays.
"""
try:
search = parse_search(json.loads(self._run_raw(_PS_WU_SEARCH)))
except PowerShellError as exc:
return {"success": False, "output": str(exc)}
updates = pending_updates(search)
security = sum(1 for u in updates if u.get("security"))
return {
"success": True,
"output": (
f"{search.origin} offers {len(updates)} updates, {security} of them for "
f"security, searched in {search.seconds} s."
),
}
def _wu_search(self) -> Search:
return parse_pending(self._run_raw(_PS_WU_PENDING))
def get_available_updates(self) -> list[UpdateDict]:
"""What the last search found, without what the host installed since.
:raises PackageIndexMissing: before the first search; a refresh searches.
"""
return pending_updates(self._wu_search())
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""The host's update history since *since* (unix seconds), newest first."""
return parse_history(self._run_raw(_PS_WU_HISTORY), since)
def apply_updates(
self,
packages: list[str],
*,
log: Callable[[str], None] | None = None,
) -> ApplyUpdatesResultDict:
"""Install the updates named *packages* -- every pending one when empty -- in a
one-shot SYSTEM task, line by line to *log*; the host is never restarted.
Each name stands for the exact updates (ID and revision) the last search found
under it; the task searches again and installs only those
(:mod:`napalm_windows.windows_update_run`).
:raises ValueError: for a name that is no package name.
:raises PackageIndexMissing: before the first search.
"""
bad = [p for p in packages if not NAME.fullmatch(p or "")]
if bad:
raise ValueError(f"Invalid update name {bad[0]!r}")
offers = self._wu_search().offers
wanted = set(packages)
chosen = [o for o in offers if not packages or o.name in wanted]
missing = sorted(wanted - {o.name for o in offers})
return install(self._run_raw, {o.identity: o.title for o in chosen}, missing, log)
+341
View File
@@ -0,0 +1,341 @@
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
Windows refuses a download or an install through the update agent to a network logon
(``E_ACCESSDENIED``), which a WinRM session is. A scheduled task running as SYSTEM is
not one, so a run is such a task (as PSWindowsUpdate's ``Invoke-WUJob`` does it):
1. **Sweep.** The tasks of earlier runs and their registry keys are deleted -- runs
whose connection died left them behind. A run still installing refuses this one.
2. **Start.** The run's key under :data:`RUNS` (``HKLM\\SOFTWARE``, where only
administrators and SYSTEM may write) gets the exact updates chosen
(``<UpdateID>:<revision>``) and the script; the task ``\\napalm-windows\\update-run-<id>``
runs that script from the key, as SYSTEM, and is started. No file is written.
3. **Follow.** Every few seconds the key's log is read and each new line handed on,
until the script writes its result, or the task ends without one.
4. **Clean up.** The task and the key are deleted.
The task searches again and installs nothing it cannot match exactly: an update no
longer offered under that ID and revision (installed, replaced or withdrawn since the
reading), one offered twice, one that asks for input while it installs, and one whose
licence terms the host has not accepted are refused, by name. While a restart is
pending, nothing is installed. The run never restarts the host: what follows a run is
the caller's. An update Windows installs with a result of its own is reported with it,
and the task names itself to Windows Update as ``napalm-windows``, as the host's
history shows.
A run the follower gives up on (:data:`FOLLOW_SECONDS`) carries on on the host: its
task is left for the next run's sweep, and what it installed shows in the history.
"""
from __future__ import annotations
import json
import time
import uuid
from collections.abc import Callable
from typing import Any
from napalm_device_types.models import ApplyUpdatesResultDict
from napalm_windows._powershell import _as_list, _ps_quote
#: Each run's own registry key lives here.
RUNS = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs"
#: The task folder of the runs; the scheduled-jobs reading shows them as an application's.
TASK_PATH = "\\napalm-windows\\"
TASK_PREFIX = "update-run-"
#: How often the follower looks, and how long it follows a run at most.
POLL_SECONDS = 5
FOLLOW_SECONDS = 25 * 60
# Runs as SYSTEM, from the run's key: search again, refuse what does not match exactly,
# download, install, report. Never restarts. __KEY__ is the run's key.
_PS_RUN = r"""
$ErrorActionPreference = 'Stop'
$key = '__KEY__'
$log = New-Object System.Collections.Generic.List[string]
$outcome = [ordered]@{
reboot_required = $false; installed = @(); refused = @(); failed = @(); error = $null
}
function Say([string]$line) {
$log.Add($line)
Set-ItemProperty -LiteralPath $key -Name Log -Value ($log -join "`n")
}
function Named($u) { '{0} ({1}:{2})' -f $u.Title, $u.Identity.UpdateID, $u.Identity.RevisionNumber }
function IdOf($u) { '{0}:{1}' -f $u.Identity.UpdateID, $u.Identity.RevisionNumber }
function Failed($u, $step, $r) {
$code = [int]$r.ResultCode
$outcome.failed += [pscustomobject]@{
id = (IdOf $u); step = $step; result = $code; hresult = [int64]$r.HResult
}
Say ('{0} failed: {1} (result {2}, 0x{3:X8})' -f $step, (Named $u), $code, [int]$r.HResult)
}
try {
$requested = @((Get-ItemProperty -LiteralPath $key -Name Requested).Requested)
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'napalm-windows'
$installer = $session.CreateUpdateInstaller()
$pending = (New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired
if ($pending -or $installer.RebootRequiredBeforeInstallation) {
throw 'A restart is pending on the host: nothing is installed until it has restarted.'
}
Say 'Searching Windows Update again for the chosen updates'
$offered = @{}
$searcher = $session.CreateUpdateSearcher()
foreach ($u in $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'").Updates) {
$id = IdOf $u
if ($offered.ContainsKey($id)) { $offered[$id] += @($u) } else { $offered[$id] = @($u) }
}
$chosen = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($id in $requested) {
$u = $null
$why = $null
if (-not $offered.ContainsKey($id)) {
$why = 'no longer offered: installed, replaced or withdrawn since it was read'
} elseif ($offered[$id].Count -ne 1) {
$why = 'offered more than once'
} else {
$u = $offered[$id][0]
if ($u.InstallationBehavior.CanRequestUserInput) {
$why = 'it asks for input while it installs'
} elseif (-not $u.EulaAccepted) {
$why = 'its licence terms have not been accepted on the host'
}
}
if ($why) {
$outcome.refused += [pscustomobject]@{ id = $id; reason = $why }
Say ('Refused {0}: {1}' -f $(if ($u) { Named $u } else { $id }), $why)
} else {
[void]$chosen.Add($u)
}
}
$ready = New-Object -ComObject Microsoft.Update.UpdateColl
if ($chosen.Count -gt 0) {
Say ('Downloading {0} update(s)' -f $chosen.Count)
$downloader = $session.CreateUpdateDownloader()
$downloader.Updates = $chosen
$fetched = $downloader.Download()
for ($i = 0; $i -lt $chosen.Count; $i++) {
$u = $chosen.Item($i)
if ($u.IsDownloaded) { [void]$ready.Add($u) }
else { Failed $u 'Download' ($fetched.GetUpdateResult($i)) }
}
}
if ($ready.Count -gt 0) {
Say ('Installing {0} update(s); the host is not restarted' -f $ready.Count)
$installer.Updates = $ready
$installer.AllowSourcePrompts = $false
try { $installer.ForceQuiet = $true } catch { }
$done = $installer.Install()
for ($i = 0; $i -lt $ready.Count; $i++) {
$u = $ready.Item($i)
$r = $done.GetUpdateResult($i)
if ($r.ResultCode -eq 2 -or $r.ResultCode -eq 3) {
$outcome.installed += (IdOf $u)
Say ('Installed: ' + (Named $u))
} else { Failed $u 'Install' $r }
if ($r.RebootRequired) { $outcome.reboot_required = $true }
}
if ($done.RebootRequired) { $outcome.reboot_required = $true }
if ($outcome.reboot_required) { Say 'A restart finishes the installation.' }
}
} catch {
$outcome.error = [string]$_.Exception.Message
if (-not $outcome.error) { $outcome.error = [string]$_ }
Say $outcome.error
}
$result = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]$outcome)
Set-ItemProperty -LiteralPath $key -Name Result -Value $result
"""
# Deletes what earlier runs left -- unless one is still running, which it names.
_PS_SWEEP = r"""
$ErrorActionPreference = 'Stop'
$tasks = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
Where-Object { $_.TaskName -like '__PREFIX__*' })
$busy = @($tasks | Where-Object { [string]$_.State -eq 'Running' } | ForEach-Object { $_.TaskName })
$swept = @()
if ($busy.Count -eq 0) {
foreach ($t in $tasks) {
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName $t.TaskName -Confirm:$false
$swept += $t.TaskName
}
if (Test-Path -LiteralPath '__RUNS__') {
foreach ($k in @(Get-ChildItem -LiteralPath '__RUNS__')) {
Remove-Item -LiteralPath $k.PSPath -Recurse
$swept += $k.PSChildName
}
}
}
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ busy = $busy; swept = $swept })
"""
_PS_START = r"""
$ErrorActionPreference = 'Stop'
$key = '__RUNS__\' + __RUN__
New-Item -Path $key -Force | Out-Null
$requested = [string[]]@(__REQUESTED__)
New-ItemProperty -LiteralPath $key -Name Requested -PropertyType MultiString -Value $requested |
Out-Null
New-ItemProperty -LiteralPath $key -Name Script -PropertyType String -Value __SCRIPT__ | Out-Null
$exe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$read = "(Get-ItemProperty -LiteralPath '$key' -Name Script).Script"
$arg = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "& ([scriptblock]::Create(' +
$read + '))"'
$action = New-ScheduledTaskAction -Execute $exe -Argument $arg
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Hours 4) -MultipleInstances IgnoreNew
$about = 'napalm-windows: installs the Windows updates an application chose; deleted when its ' +
'run ends'
Register-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Action $action `
-Principal $principal -Settings $settings -Description $about | Out-Null
Start-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__
"""
# The task's state first: a result written after it was read is still found below.
_PS_FOLLOW = r"""
$ErrorActionPreference = 'Stop'
$task = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
Where-Object { $_.TaskName -eq __TASK__ })
$state = 'gone'
if ($task.Count) { $state = [string]$task[0].State }
$run = Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath ('__RUNS__\' + __RUN__)
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{
state = $state
log = [string]$run.Log
result = [string]$run.Result
})
"""
_PS_CLEANUP = r"""
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Confirm:$false `
-ErrorAction SilentlyContinue
$key = '__RUNS__\' + __RUN__
if (Test-Path -LiteralPath $key) { Remove-Item -LiteralPath $key -Recurse }
"""
def _script(template: str, **values: str) -> str:
"""*template* with its ``__NAME__`` placeholders filled; the run's own as given, the
module's constants always. Values are PowerShell already: quote them first."""
values = {"PATH": TASK_PATH, "PREFIX": TASK_PREFIX, "RUNS": RUNS, **values}
for name, value in values.items():
template = template.replace(f"__{name}__", value)
return template
Run = Callable[[str], str]
Log = Callable[[str], None]
class _Lines:
"""Every line of the run, each handed to *log* once as it comes."""
def __init__(self, log: Log | None):
self.log = log
self.lines: list[str] = []
def say(self, line: str) -> None:
self.lines.append(line)
if self.log is not None:
self.log(line)
def host(self, text: str, seen: int) -> int:
"""Hand on the lines of the host's *text* past the first *seen*; how many there are."""
lines = text.split("\n") if text else []
for line in lines[seen:]:
self.say(line)
return max(len(lines), seen)
def result(self, success: bool, error: str | None = None) -> ApplyUpdatesResultDict:
out: ApplyUpdatesResultDict = {"success": success, "output": "\n".join(self.lines)}
if not success:
out["error"] = error or "The update run did not succeed; its output says why."
return out
def _ids(run_id: str) -> dict[str, str]:
return {"RUN": _ps_quote(run_id), "TASK": _ps_quote(TASK_PREFIX + run_id)}
def _sweep(run: Run) -> list[str]:
"""The earlier runs still installing; the others are deleted."""
reading = json.loads(run(_script(_PS_SWEEP)) or "{}")
return [str(b) for b in _as_list(reading.get("busy"))]
def run_script(run_id: str) -> str:
"""What the task runs as SYSTEM for the run *run_id*."""
return _PS_RUN.replace("__KEY__", f"{RUNS}\\{run_id}")
def _start(run: Run, run_id: str, identities: list[str]) -> None:
requested = ",".join(_ps_quote(i) for i in identities)
script = _ps_quote(run_script(run_id))
run(_script(_PS_START, REQUESTED=requested, SCRIPT=script, **_ids(run_id)))
def _cleanup(run: Run, run_id: str) -> None:
run(_script(_PS_CLEANUP, **_ids(run_id)))
def _outcome(result: dict[str, Any], lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
refused = len(_as_list(result.get("refused"))) + refused_before
failed = len(_as_list(result.get("failed")))
if result.get("error"):
return lines.result(False, str(result["error"]))
if refused or failed:
return lines.result(False, f"{refused} update(s) refused, {failed} failed.")
return lines.result(True)
def _follow(run: Run, run_id: str, lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
"""Hand on the run's lines until it ends; its outcome."""
seen = 0
deadline = time.monotonic() + FOLLOW_SECONDS
follow = _script(_PS_FOLLOW, **_ids(run_id))
while True:
time.sleep(POLL_SECONDS)
reading = json.loads(run(follow) or "{}")
seen = lines.host(str(reading.get("log") or ""), seen)
if reading.get("result"):
_cleanup(run, run_id)
return _outcome(json.loads(reading["result"]), lines, refused_before)
if reading.get("state") != "Running":
_cleanup(run, run_id)
return lines.result(False, "The update task ended without a result.")
if time.monotonic() > deadline:
return lines.result(
False,
"The updates are still installing on the host; the run carries on there, "
"and the update history shows what it installed.",
)
def install(
run: Run, chosen: dict[str, str], missing: list[str], log: Log | None
) -> ApplyUpdatesResultDict:
"""Install the updates *chosen* (``identity -> title``) in a SYSTEM task, following it.
*missing* are names the caller asked for that the last search does not offer: each
is refused, by name, and the others are installed.
"""
lines = _Lines(log)
for name in missing:
lines.say(f"Refused {name}: not offered by the last search")
if not chosen:
if missing:
return lines.result(False, f"{len(missing)} update(s) refused, 0 failed.")
lines.say("Nothing to install.")
return lines.result(True)
busy = _sweep(run)
if busy:
lines.say(f"An earlier update run is still installing on the host: {', '.join(busy)}")
return lines.result(False, "An earlier update run is still installing on the host.")
run_id = uuid.uuid4().hex[:12]
for identity, title in chosen.items():
lines.say(f"Chosen: {title} ({identity})")
_start(run, run_id, list(chosen))
return _follow(run, run_id, lines, len(missing))
+6 -8
View File
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-windows"
version = "0.2.0"
version = "0.3.0"
description = "NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)"
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.12"
license = "Apache-2.0"
authors = [
{ name = "Christian Manivong", email = "christian@manivong.de" },
@@ -28,8 +28,6 @@ classifiers = [
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: System :: Networking",
@@ -37,8 +35,8 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"napalm>=4.0",
"napalm-device-types>=4.21.1",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.56.0", # HostStorageMixin, HostRepairMixin, host events, UserDict.sid
"pypsrp>=0.8",
]
@@ -67,7 +65,7 @@ napalm_windows = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -77,7 +75,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
+8
View File
@@ -8,3 +8,11 @@ and the Python side is tested against it here.
What they cannot prove is that the scripts produce this shape on a real host
(property names, Windows PowerShell 5.1 serialisation quirks). They are to be
replaced by output recorded from a Windows Server and a Windows 11 client.
`login_accounts_server_de.json` is a German-language domain member and
`login_accounts_client.json` a Windows 11 workgroup client, `login_sessions.json` a
domain member's Security log; their account names, SIDs and addresses are made up
(documentation ranges).
The repair runs' fixtures (`*.txt`) are what their scripts stream: one output object
per line, ending in `napalm-exit-code:<n>`. They follow Microsoft's documented output of
`sfc`, `DISM` and the Defender cmdlets; `tools/harvest.py --runs` records the real ones.
+5
View File
@@ -0,0 +1,5 @@
Scan started: QuickScan
Scan ended.
Threats detected: 1
Virus:DOS/EICAR_Test_File: action succeeded
napalm-exit-code:0
@@ -0,0 +1,3 @@
Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC
Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC
napalm-exit-code:0
+102
View File
@@ -0,0 +1,102 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "eui.0025385A11B22C33",
"name": "Samsung SSD 980 PRO 1TB",
"model": "Samsung SSD 980 PRO 1TB",
"vendor": "",
"serial": "0025_385A_11B2_2C33.",
"media_type": "SSD",
"bus_type": "NVMe",
"health": "Healthy",
"size": 1000204886016,
"spindle": 0,
"pool": null,
"counter": {
"temperature": 41,
"temperature_max": 68,
"wear": 3,
"power_on_hours": 5120,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
},
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": " WD-WCC7K1ABCDEF",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Warning",
"size": 4000787030016,
"spindle": 5400,
"pool": "Pool1",
"counter": {
"temperature": 36,
"temperature_max": 51,
"wear": 0,
"power_on_hours": 31012,
"read_errors_uncorrected": 12,
"write_errors_uncorrected": 0
}
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5",
"name": "WDC WD40EFRX-68N32N0",
"model": "WDC WD40EFRX-68N32N0",
"vendor": "",
"serial": "WD-WCC7K1ABCDF0",
"media_type": "HDD",
"bus_type": "SATA",
"health": "Healthy",
"size": 4000787030016,
"spindle": 4294967295,
"pool": "Pool1",
"counter": {
"temperature": 0,
"temperature_max": null,
"wear": 0,
"power_on_hours": 30990,
"read_errors_uncorrected": null,
"write_errors_uncorrected": null
}
},
{
"device_id": "4",
"unique_id": "600508B1001C5A6B7C8D9E0F1A2B3C4D",
"name": "HPE LOGICAL VOLUME",
"model": "LOGICAL VOLUME",
"vendor": "HPE",
"serial": "PDNLH0BRH9A1B2",
"media_type": "Unspecified",
"bus_type": "RAID",
"health": "Healthy",
"size": 1200210141184,
"spindle": 4294967295,
"pool": null,
"counter": null
},
{
"device_id": "",
"unique_id": "{6b2f0c1e-0b5a-4a5e-9d3f-1c2b3a4d5e6f}",
"name": "Data",
"model": "Storage Space",
"vendor": "Microsoft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "Spaces",
"health": "Healthy",
"size": 2199023255552,
"spindle": 0,
"pool": null,
"counter": null
}
]
}
+28
View File
@@ -0,0 +1,28 @@
{
"supported": true,
"counters": true,
"disks": [
{
"device_id": "0",
"unique_id": "60022480A1B2C3D4E5F60718293A4B5C",
"name": "Msft Virtual Disk",
"model": "Virtual Disk",
"vendor": "Msft",
"serial": "",
"media_type": "Unspecified",
"bus_type": "SAS",
"health": "Healthy",
"size": 136365211648,
"spindle": 4294967295,
"pool": null,
"counter": {
"temperature": 0,
"temperature_max": 0,
"wear": 0,
"power_on_hours": null,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0
}
}
]
}
+10
View File
@@ -0,0 +1,10 @@
Deployment Image Servicing and Management tool
Version: 10.0.20348.681
Image Version: 10.0.20348.2340
[===== 10.0% ]
[==========================100.0%==========================] No component store corruption detected.
The operation completed successfully.
napalm-exit-code:0
+14
View File
@@ -0,0 +1,14 @@
Deployment Image Servicing and Management tool
Version: 10.0.20348.681
Image Version: 10.0.20348.2340
Error: 0x800f081f
The source files could not be found.
Use the "Source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see https://go.microsoft.com/fwlink/?LinkId=243077.
The DISM log file can be found at C:\Windows\Logs\DISM\dism.log
napalm-exit-code:-2146498529
+11
View File
@@ -0,0 +1,11 @@
[
{"channel": "Application", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Application.evtx", "size": 20975616, "modified": 1764499800, "records": 41233, "type": "Administrative"},
{"channel": "Security", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Security.evtx", "size": 20975616, "modified": 1764499990, "records": 58812, "type": "Administrative"},
{"channel": "System", "path": "C:\\Windows\\System32\\Winevt\\Logs\\System.evtx", "size": 20975616, "modified": 1764499950, "records": 30187, "type": "Administrative"},
{"channel": "Microsoft-Windows-Sysmon/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Sysmon%4Operational.evtx", "size": 67113984, "modified": 1764499999, "records": 120044, "type": "Operational"},
{"channel": "Microsoft-Windows-PowerShell/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-PowerShell%4Operational.evtx", "size": 15798272, "modified": null, "records": 9120, "type": "Operational"},
{"channel": "Microsoft-Windows-Kernel-PnP/Device Management", "path": null, "size": 69632, "modified": 1764400000, "records": 12, "type": "Operational"},
{"channel": "Microsoft-Windows-WMI-Activity/Debug", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-WMI-Activity%4Debug.etl", "size": 4096, "modified": 1764400000, "records": 3, "type": "Debug"},
{"channel": "Microsoft-Windows-Kernel-Boot/Analytic", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Kernel-Boot%4Analytic.etl", "size": 4096, "modified": 1764400000, "records": 7, "type": "Analytic"},
{"channel": "Microsoft-Windows-Empty/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Empty%4Operational.evtx", "size": 69632, "modified": 1764400000, "records": 0, "type": "Operational"}
]
+217
View File
@@ -0,0 +1,217 @@
{
"parts": {
"rare": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Microsoft-Windows-WER-SystemErrorReporting",
"id": 1001,
"time": 1764470150,
"props": [
"0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50)",
"C:\\Windows\\MEMORY.DMP",
"1130-01"
],
"message": "The computer has rebooted from a bugcheck. The bugcheck was: 0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50). A dump was saved in: C:\\Windows\\MEMORY.DMP. Report Id: 1130-01."
},
{
"provider": "EventLog",
"id": 6008,
"time": 1764470040,
"props": [
"03:12:09",
"\u200e30.\u200e11.\u200e2026",
"",
"",
"1234",
"",
""
],
"message": "The previous system shutdown at 03:12:09 on 30.11.2026 was unexpected."
},
{
"provider": "Microsoft-Windows-Kernel-Power",
"id": 41,
"time": 1764470035,
"props": [
"159",
"3",
"18446676388826430528",
"18446735294628329080",
"18446676388826430800",
"false",
"0"
],
"message": "The system has rebooted without cleanly shutting down first."
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 18,
"time": 1764383600,
"props": [
"1",
"0",
"5",
"0",
"0"
],
"message": "A fatal hardware error has occurred."
},
{
"provider": "disk",
"id": 7,
"time": 1764466400,
"props": [
"\\Device\\Harddisk1\\DR1"
],
"message": "The device, \\Device\\Harddisk1\\DR1, has a bad block."
},
{
"provider": "Microsoft-Windows-Ntfs",
"id": 55,
"time": 1764462800,
"props": [
"D:",
"\\Device\\HarddiskVolume5",
"0x2"
],
"message": "A corruption was discovered in the file system structure on volume D:."
},
{
"provider": "Microsoft-Windows-Kernel-Power",
"id": 41,
"time": 1764297200,
"props": [
"0",
"0",
"0",
"0",
"0",
"false",
"0"
],
"message": null
}
]
},
"frequent": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Service Control Manager",
"id": 7031,
"time": 1764470600,
"props": [
"Backup Agent",
"1",
"60000",
"1",
"Restart the service"
],
"message": null
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 47,
"time": 1764470500,
"props": [
"3",
"0",
"1"
],
"message": null
},
{
"provider": "disk",
"id": 153,
"time": 1764470400,
"props": [
"\\Device\\Harddisk1\\DR1",
"0x1d4c0",
"1",
"\\Device\\00000034"
],
"message": null
},
{
"provider": "Service Control Manager",
"id": 7034,
"time": 1764470300,
"props": [
"Vendor Sync",
"2"
],
"message": null
},
{
"provider": "Microsoft-Windows-WHEA-Logger",
"id": 19,
"time": 1764470200,
"props": [
"3",
"0",
"1"
],
"message": null
}
]
},
"apps": {
"ok": true,
"capped": false,
"events": [
{
"provider": "Application Error",
"id": 1000,
"time": 1764470900,
"props": [
"vendorapp.exe",
"4.2.0.0",
"65a1b2c3",
"ntdll.dll",
"10.0.20348.2340",
"f0e1d2c3",
"c0000005",
"00000000000a1b2c",
"1f40",
"01db1234567890ab",
"C:\\Program Files\\Vendor\\vendorapp.exe"
],
"message": null
},
{
"provider": "Application Error",
"id": 1000,
"time": 1764470800,
"props": [
"vendorapp.exe",
"4.2.0.0",
"65a1b2c3",
"ntdll.dll",
"10.0.20348.2340",
"f0e1d2c3",
"c0000005",
"00000000000a1b2c",
"1f40",
"01db1234567890ab",
"C:\\Program Files\\Vendor\\vendorapp.exe"
],
"message": null
},
{
"provider": "Application Error",
"id": 1000,
"time": 1764470700,
"props": [
"legacy.exe",
"1.0.0.0",
"5f0a0b0c"
],
"message": null
}
]
}
}
}
+72
View File
@@ -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
View File
@@ -0,0 +1 @@
{"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}}
+113
View File
@@ -0,0 +1,113 @@
{
"computer": "WIN11-01",
"domain_role": 0,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Guest",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "alice",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\alice",
"last_logon": 1764543600000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 1,
"locked_out": false
},
{
"name": "bob",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": "C:\\Users\\bob",
"last_logon": 1763942400000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administrators",
"members": [
{
"path": "WinNT://WORKGROUP/WIN11-01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://WORKGROUP/WIN11-01/alice",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remote Desktop Users",
"members": []
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": []
},
"rdp_deny": "1",
"rdp_deny_policy": null,
"errors": []
}
+147
View File
@@ -0,0 +1,147 @@
{
"computer": "SRV01",
"domain_role": 3,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": true,
"home": "C:\\Users\\Administrator",
"last_logon": 1764374400000,
"password_last_set": 1747267200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Gast",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "helpdesk",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\helpdesk",
"last_logon": 1754179200000,
"password_last_set": 1753315200000,
"password_expires": 1761091200000,
"account_expires": null,
"bad_passwords": 7,
"locked_out": true
},
{
"name": "svc-backup",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": null,
"last_logon": 1764460800000,
"password_last_set": 1763683200000,
"password_expires": null,
"account_expires": 1764115200000,
"bad_passwords": null,
"locked_out": null
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administratoren",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://CONTOSO/Domänen-Admins",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-512"
},
{
"path": "WinNT://CONTOSO/jdoe",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107"
},
{
"path": "WinNT://S-1-5-21-3623811015-3361044348-30300820-1290",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1290"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remotedesktopbenutzer",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/helpdesk",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
},
{
"path": "WinNT://CONTOSO/RDP-Operators",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1301"
}
]
},
{
"sid": "S-1-5-32-546",
"name": "Gäste",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Gast",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501"
}
]
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": [
"*S-1-5-32-546"
]
},
"rdp_deny": "0",
"rdp_deny_policy": null,
"errors": []
}
+109
View File
@@ -0,0 +1,109 @@
{
"computer": "SRV01",
"canary": true,
"own_ip": "198.51.100.2",
"winrm_peers": [
"198.51.100.2"
],
"oldest": 1764288000000,
"logons": [
{
"t": 1764543600000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "900001",
"type": "10",
"ip": "198.51.100.2",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100001",
"type": "10",
"ip": "192.0.2.10",
"linked": "100002"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100002",
"type": "10",
"ip": "192.0.2.10",
"linked": "100001"
},
{
"t": 1764529200000,
"sid": "S-1-5-90-0-2",
"user": "DWM-2",
"domain": "Window Manager",
"id": "100003",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-96-0-2",
"user": "UMFD-2",
"domain": "Font Driver Host",
"id": "100004",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764453600000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"user": "Administrator",
"domain": "SRV01",
"id": "200001",
"type": "2",
"ip": "127.0.0.1",
"linked": "0"
},
{
"t": 1764367200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "300001",
"type": "11",
"ip": "-",
"linked": "0"
},
{
"t": 1764540000000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"user": "helpdesk",
"domain": "SRV01",
"id": "400001",
"type": "10",
"ip": "2001:db8::10",
"linked": "0"
}
],
"ends": [
{
"t": 1764536400000,
"id": "100001"
},
{
"t": 1764536400005,
"id": "100002"
},
{
"t": 1764457200000,
"id": "200001"
},
{
"t": 1764187200000,
"id": "400001"
}
]
}
+1
View File
@@ -0,0 +1 @@
{"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
View File
@@ -0,0 +1 @@
[{"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
View File
@@ -0,0 +1 @@
{"system_drive":"C:","secure_boot":"True","tpm":{"present":true,"enabled":true,"activated":true,"owned":true,"spec_version":"2.0, 0, 1.59","manufacturer":"INTC"},"bitlocker":{"installed":true,"volumes":[{"drive":"C:","volume_type":"0","protection":"1","conversion":"1","method":"6"},{"drive":"D:","volume_type":"1","protection":"0","conversion":"0","method":"0"}]},"defender":{"am_service":true,"antivirus":true,"real_time":true,"running_mode":"Normal","signature_updated":1764547200,"signature_age":0,"signature_version":"1.443.512.0","tamper_protected":true},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"True"},{"name":"Public","enabled":"True"}],"vbs":{"status":"2","running":["1","2"]},"errors":{}}
+1
View File
@@ -0,0 +1 @@
{"system_drive":"C:","secure_boot":"unsupported","tpm":{"present":false},"bitlocker":{"installed":false,"volumes":[]},"defender":{"am_service":true,"antivirus":true,"real_time":false,"running_mode":"Passive Mode","signature_updated":1763942400,"signature_age":7,"signature_version":"1.443.300.0","tamper_protected":false},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"False"},{"name":"Public","enabled":"True"}],"vbs":{"status":"0","running":["0"]},"errors":{}}
+1
View File
@@ -0,0 +1 @@
{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]}
+100
View File
@@ -0,0 +1,100 @@
{
"time_zone": "W. Europe Standard Time",
"count": 5,
"tasks": [
{
"path": "\\Microsoft\\Windows\\Defrag\\",
"name": "ScheduledDefrag",
"state": "Ready",
"user": "SYSTEM",
"group": null,
"on_demand": true,
"description": "This task optimizes local storage drives.",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%windir%\\system32\\defrag.exe", "arguments": "-c -h -o -$", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskWeeklyTrigger", "enabled": true, "start": "2026-01-01T01:00:00", "days_interval": null, "weeks_interval": 1, "days_of_week": 1, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-01T00:00:12.0000000Z",
"last_result": 0,
"next_run": "2026-11-08T00:00:00.0000000Z"
},
{
"path": "\\Microsoft\\Windows\\UpdateOrchestrator\\",
"name": "Reboot",
"state": "Disabled",
"user": "SYSTEM",
"group": null,
"on_demand": true,
"description": null,
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%systemroot%\\system32\\MusNotification.exe", "arguments": "RebootDialog", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskTimeTrigger", "enabled": true, "start": "2026-11-04T03:00:00+01:00", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "1999-11-29T23:00:00.0000000Z",
"last_result": 267011,
"next_run": null
},
{
"path": "\\",
"name": "Admin's backup",
"state": "Ready",
"user": "Administrator",
"group": null,
"on_demand": true,
"description": "Copies D:\\data to the NAS",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "robocopy.exe", "arguments": "D:\\data \\\\nas\\backup /MIR", "class_id": null},
{"class": "MSFT_TaskExecAction", "execute": "C:\\scripts\\notify.cmd", "arguments": null, "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskDailyTrigger", "enabled": true, "start": "2026-01-01T00:00:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "PT1H", "duration": "P1D", "delay": ""},
{"class": "MSFT_TaskDailyTrigger", "enabled": false, "start": "2026-01-01T12:30:00", "days_interval": 2, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "/Date(1793854800000)/",
"last_result": 2147942402,
"next_run": "/Date(1793858400000)/"
},
{
"path": "\\",
"name": "nightly-dump",
"state": "Ready",
"user": "backup",
"group": null,
"on_demand": true,
"description": "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *",
"actions": [
{"class": "MSFT_TaskExecAction", "execute": "%SystemRoot%\\System32\\cmd.exe", "arguments": "/d /s /c \"pg_dump -f D:\\dump.sql app\"", "class_id": null}
],
"triggers": [
{"class": "MSFT_TaskTrigger", "enabled": true, "start": "2020-01-01T02:30:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-03T01:30:04.1234567Z",
"last_result": 1,
"next_run": "2026-11-04T01:30:00Z"
},
{
"path": "\\Vendor\\",
"name": "Updater",
"state": "Running",
"user": null,
"group": "Users",
"on_demand": false,
"description": "",
"actions": [
{"class": "MSFT_TaskComHandlerAction", "execute": null, "arguments": null, "class_id": "{A6BA00FE-40E8-477C-B713-C64A14F18ADB}"}
],
"triggers": [
{"class": "MSFT_TaskLogonTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": "PT15M"},
{"class": "MSFT_TaskBootTrigger", "enabled": null, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""},
{"class": "MSFT_TaskSessionStateChangeTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
],
"last_run": "2026-11-03T06:00:00Z",
"last_result": 267009,
"next_run": null
}
]
}
+9 -5
View File
@@ -1,7 +1,11 @@
[
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234},
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0},
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321},
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0},
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null}
{"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234, "exit_code": 0, "service_code": 0, "account": "NT AUTHORITY\\NetworkService", "trigger_start": false},
{"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
{"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321, "exit_code": 0, "service_code": 0, "account": "CORP\\svc-sql", "trigger_start": false},
{"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "NT AUTHORITY\\LocalService", "trigger_start": true},
{"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": true},
{"name": "AppReadiness", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "LocalSystem", "trigger_start": false},
{"name": "BackupAgent", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1067, "service_code": 0, "account": "CORP\\svc-backup", "trigger_start": false},
{"name": "VendorSync", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1066, "service_code": 2147942405, "account": "LocalSystem", "trigger_start": false},
{"name": "BthServ", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1, "service_code": 0, "account": null, "trigger_start": true}
]
+10
View File
@@ -0,0 +1,10 @@
Beginning system scan. This process will take some time.
Beginning verification phase of system scan.
Verification 1% complete.
Verification 52% complete.
Verification 100% complete.
Windows Resource Protection did not find any integrity violations.
napalm-exit-code:0
+26
View File
@@ -0,0 +1,26 @@
{
"supported": true,
"pools": [
{
"name": "Pool1",
"health": "Warning",
"operational": [
"Degraded"
],
"size": 8001574060032,
"allocated": 2199023255552,
"resiliency": "Mirror",
"read_only": false,
"disks": [
{
"device_id": "1",
"unique_id": "50014EE2B1C2D3E4"
},
{
"device_id": "3",
"unique_id": "50014EE2B1C2D3F5"
}
]
}
]
}
+1
View File
@@ -0,0 +1 @@
{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600}
+1
View File
@@ -0,0 +1 @@
{"type":"NTP","ntp_server":"time.windows.com,0x9","policy_type":null,"policy_server":null,"service":"Running","status":"Leap Indicator: 0(no warning)\nStratum: 4 (secondary reference - syncd by (S)NTP)\nPrecision: -23 (119.209ns per tick)\nRoot Delay: 0.0312500s\nRoot Dispersion: 7.9876543s\nReferenceId: 0x14650039 (source IP: 20.101.57.9)\nLast Successful Sync Time: 11/11/2026 10:00:00 AM\nSource: time.windows.com,0x9\nPoll Interval: 10 (1024s)\n","zone":"W. Europe Standard Time","dst_off":"0","iana_zone":null}
+61
View File
@@ -0,0 +1,61 @@
{
"supported": true,
"volumes": [
{
"letter": "C",
"label": "",
"file_system": "NTFS",
"size": 999483936768,
"remaining": 712345698304,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-100000000000}\\",
"mounts": [
"C:\\"
]
},
{
"letter": "D",
"label": "Data",
"file_system": "ReFS",
"size": 2196875771904,
"remaining": 109521666048,
"health": "Warning",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-200000000000}\\",
"mounts": [
"D:\\"
]
},
{
"letter": "",
"label": "Logs",
"file_system": "NTFS",
"size": 1200191766528,
"remaining": 1100000000000,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-300000000000}\\",
"mounts": [
"C:\\Logs\\"
]
},
{
"letter": "",
"label": "",
"file_system": "FAT32",
"size": 104857600,
"remaining": 71303168,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-400000000000}\\",
"mounts": []
},
{
"letter": "",
"label": "",
"file_system": "NTFS",
"size": 681574400,
"remaining": 98566144,
"health": "Healthy",
"path": "\\\\?\\Volume{1f2e3d4c-0000-0000-0000-500000000000}\\",
"mounts": []
}
]
}
+8
View File
@@ -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}
]
+1
View File
@@ -0,0 +1 @@
[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","at":1795603600,"operation":1,"result":2,"hresult":0,"client":"Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)"},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","at":1795590000,"operation":1,"result":4,"hresult":-2145124329,"client":"napalm-windows"},{"id":"aa11bb22-cc33-4d44-8e55-ff6677889900","revision":1,"title":"2026-10 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5066000)","at":1792900000,"operation":1,"result":2,"hresult":0,"client":"UpdateOrchestrator"},{"id":"bb22cc33-dd44-4e55-8f66-0011aabbccdd","revision":2,"title":"Update for Windows Security platform - KB5007651 (Version 1.0.2509.1001)","at":1792800000,"operation":2,"result":2,"hresult":0,"client":"AutomaticUpdates"},{"id":"cc33dd44-ee55-4f66-8a77-1122bbccddee","revision":1,"title":"2026-09 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5063000)","at":1790200000,"operation":1,"result":1,"hresult":0,"client":""}]
+1
View File
@@ -0,0 +1 @@
{"search":"{\"searched_at\":1795600000,\"finished_at\":1795600094,\"result\":2,\"wsus\":null,\"updates\":[{\"id\":\"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11\",\"revision\":1,\"title\":\"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)\",\"kb\":[\"5070000\"],\"cves\":[\"CVE-2026-21001\",\"CVE-2026-21002\",\"CVE-2026-21003\"],\"severity\":\"Critical\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":2,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4\",\"revision\":200,\"title\":\"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)\",\"kb\":[\"2267602\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"e0789628-ce08-4437-be74-2495b842f43b\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":true},{\"id\":\"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f\",\"revision\":3,\"title\":\"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)\",\"kb\":[\"5070100\"],\"cves\":[\"CVE-2026-21101\"],\"severity\":\"Important\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c\",\"revision\":1,\"title\":\"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)\",\"kb\":[\"890830\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"28bc880e-0592-4cbf-8f95-c79b17911d5f\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b\",\"revision\":1,\"title\":\"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)\",\"kb\":[\"5070200\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83\"],\"browse_only\":true,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d\",\"revision\":1,\"title\":\"Windows Server 2025 upgrade\",\"kb\":[],\"cves\":[],\"severity\":\"\",\"classifications\":[\"3689bdc8-b205-4af4-8d4a-a63924c5e9d5\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":false,\"downloaded\":false}]}","installed":[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"at":1795603600},{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"at":1795500000}],"history_error":null}
+1
View File
@@ -0,0 +1 @@
{"searched_at":1795600000,"finished_at":1795600094,"result":2,"wsus":null,"updates":[{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"title":"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)","kb":["5070000"],"cves":["CVE-2026-21001","CVE-2026-21002","CVE-2026-21003"],"severity":"Critical","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":2,"eula_accepted":true,"downloaded":false},{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","kb":["2267602"],"cves":[],"severity":"","classifications":["e0789628-ce08-4437-be74-2495b842f43b"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":true},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","kb":["5070100"],"cves":["CVE-2026-21101"],"severity":"Important","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c","revision":1,"title":"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)","kb":["890830"],"cves":[],"severity":"","classifications":["28bc880e-0592-4cbf-8f95-c79b17911d5f"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b","revision":1,"title":"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)","kb":["5070200"],"cves":[],"severity":"","classifications":["cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83"],"browse_only":true,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d","revision":1,"title":"Windows Server 2025 upgrade","kb":[],"cves":[],"severity":"","classifications":["3689bdc8-b205-4af4-8d4a-a63924c5e9d5"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":false,"downloaded":false}]}
+103
View File
@@ -0,0 +1,103 @@
"""The event channels as the host's log sources (NetOrk/netork#2897).
A Windows host keeps its logs in event channels. ``Get-WinEvent -ListLog *`` names
every one with its ``.evtx`` file, size, last write and record count; a channel that
is switched on and holds records is a log the host writes. Analytic and debug
channels are trace sessions, not logs a reader can follow, and are left out. The
answer is the shape of tests/fixtures/synthetic/event_channels.json.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import event_channels as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "event_channels.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(answer: str | None = None) -> dict:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
return d.get_log_sources()
class TestTheReading:
def test_read_as_an_administrator_without_a_journal(self):
reading = _reading()
assert (reading["attributed"], reading["journald"], reading["forwarding"]) == (
True,
False,
None,
)
def test_every_channel_with_records_sorted_by_name(self):
assert [s["channel"] for s in _reading()["sources"]] == [
"Application",
"Microsoft-Windows-Kernel-PnP/Device Management",
"Microsoft-Windows-PowerShell/Operational",
"Microsoft-Windows-Sysmon/Operational",
"Security",
"System",
]
def test_a_channel_is_an_eventlog_source(self):
sysmon = next(s for s in _reading()["sources"] if "Sysmon" in s["channel"])
assert sysmon == {
"kind": "eventlog",
"path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx",
"unit": None,
"container_id": None,
"process": None,
"size": 67113984,
"modified": "2025-11-30T10:53:19+00:00",
"channel": "Microsoft-Windows-Sysmon/Operational",
}
def test_what_the_host_did_not_say_is_none(self):
sources = {s["channel"]: s for s in _reading()["sources"]}
assert sources["Microsoft-Windows-PowerShell/Operational"]["modified"] is None
assert sources["Microsoft-Windows-Kernel-PnP/Device Management"]["path"] is None
@pytest.mark.parametrize("left_out", ["Debug", "Analytic", "Empty"])
def test_trace_sessions_and_empty_channels_are_left_out(self, left_out):
assert not any(left_out in s["channel"] for s in _reading()["sources"])
def test_a_single_channel_is_still_a_list(self):
one = json.loads(FIXTURE.read_text())[2]
assert [s["channel"] for s in _reading(json.dumps(one))["sources"]] == ["System"]
def test_no_channel_is_no_sources(self):
assert _reading("")["sources"] == []
class TestTheScript:
def test_lists_every_channel_once(self):
assert "Get-WinEvent -ListLog *" in mod._PS_EVENT_CHANNELS
def test_a_channel_it_may_not_open_costs_only_that_channel(self):
assert "-ErrorAction SilentlyContinue" in mod._PS_EVENT_CHANNELS
def test_only_channels_switched_on_and_holding_records(self):
assert "$_.IsEnabled -and $_.RecordCount" in mod._PS_EVENT_CHANNELS
def test_the_file_is_named_as_it_is_on_disk(self):
assert "ExpandEnvironmentVariables" in mod._PS_EVENT_CHANNELS
def test_a_list_goes_through_input_object(self):
assert "-InputObject @(" in mod._PS_EVENT_CHANNELS
+206
View File
@@ -0,0 +1,206 @@
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
One script asks the event log three questions over the reading's window: the rare
events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware
error, a bad block, a file system corruption), its frequent ones (corrected
hardware errors, retried disk I/O, services that ended unexpectedly) and the
Application log's crashing programs. Each is bounded by time and count, and each
catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The
answer is the shape of tests/fixtures/synthetic/host_events.json.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin
from napalm_windows import WindowsDriver
from napalm_windows import host_events as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json"
NOW = 1764500000.0
WEEK = 7 * 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 _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver:
if answer is None:
answer = FIXTURE.read_text()
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer))
return d
def _fixture() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
@pytest.fixture(autouse=True)
def _now(monkeypatch):
monkeypatch.setattr(mod.time, "time", lambda: NOW)
def _kinds(reading) -> list[tuple[str, str | None]]:
return [(e["kind"], e["subject"]) for e in reading["events"]]
class TestTheEvents:
def test_every_event_as_its_kind_and_subject_newest_first(self):
assert _kinds(_driver().get_host_events()) == [
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
("app_crash", "legacy.exe"),
("service_crash", "Backup Agent"),
("hardware_error_corrected", None),
("disk_error", r"\Device\Harddisk1\DR1"),
("service_crash", "Vendor Sync"),
("hardware_error_corrected", None),
("system_crash", "0x0000009f"),
("unexpected_shutdown", None),
("unexpected_shutdown", "0x0000009f"),
("disk_error", r"\Device\Harddisk1\DR1"),
("disk_error", "D:"),
("hardware_error_fatal", None),
("unexpected_shutdown", None),
]
def test_an_event_says_when_where_and_what_the_host_wrote(self):
crash = next(
e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash"
)
assert crash == {
"kind": "system_crash",
"time": "2025-11-30T02:35:50+00:00",
"subject": "0x0000009f",
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
"message": crash["message"],
}
assert crash["message"].startswith("The computer has rebooted from a bugcheck.")
def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self):
shutdowns = [
e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown"
]
assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None]
def test_the_hosts_message_is_cut(self):
answer = _fixture()
answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000
events = _driver(answer).get_host_events()["events"]
assert max(len(e["message"] or "") for e in events) == 300
def test_an_event_the_reading_does_not_know_is_left_out(self):
answer = _fixture()
answer["parts"]["rare"]["events"] = [
{"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []}
]
kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]}
assert "unexpected_shutdown" not in kinds
def test_a_single_event_is_still_a_list(self):
answer = _fixture()
answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0]
apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"]
assert len(apps) == 1
class TestWhatWasRead:
def test_a_full_reading_names_nothing_capped_or_unread(self):
reading = _driver().get_host_events()
assert (reading["capped"], reading["unread"]) == ([], [])
def test_an_empty_log_is_no_events_not_an_error(self):
"""What the script makes of ``NoMatchingEventsFound``: read, nothing found."""
answer = _fixture()
for part in answer["parts"].values():
part["events"] = []
reading = _driver(answer).get_host_events()
assert (reading["events"], reading["unread"]) == ([], [])
def test_a_query_that_failed_names_its_kinds_unread(self):
answer = _fixture()
answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"}
reading = _driver(answer).get_host_events()
assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"]
assert "service_crash" not in {e["kind"] for e in reading["events"]}
def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self):
answer = _fixture()
answer["parts"]["apps"]["capped"] = True
assert _driver(answer).get_host_events()["capped"] == ["app_crash"]
def test_a_part_missing_from_the_answer_is_unread(self):
answer = _fixture()
del answer["parts"]["apps"]
assert _driver(answer).get_host_events()["unread"] == ["app_crash"]
def test_every_kind_is_read_by_some_query(self):
read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds}
assert read == set(HOST_EVENT_KINDS)
@pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}'])
def test_an_answer_without_a_report_raises(self, answer):
with pytest.raises(ValueError):
_driver(answer).get_host_events()
class TestTheWindow:
def test_a_week_by_default(self):
d = _driver()
reading = d.get_host_events()
assert reading["since"] == "2025-11-23T10:53:20+00:00"
assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0]
def test_the_callers_start(self):
d = _driver()
reading = d.get_host_events(since=NOW - 3600)
assert reading["since"] == "2025-11-30T09:53:20+00:00"
assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0]
class TestTheScript:
script = mod.host_events_script(NOW - WEEK)
def test_every_query_catches_no_matching_events(self):
assert self.script.count("Get-WinEvent") == 1
assert "NoMatchingEventsFound" in self.script
assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3
def test_every_query_is_bounded_by_count(self):
bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)]
assert bounds == [100, 500, 200]
assert "-MaxEvents $max" in self.script
def test_every_query_is_bounded_by_time(self):
assert self.script.count("TimeCreated[@SystemTime>=") == 3
def test_only_the_rare_events_carry_their_message(self):
assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [
"true",
"false",
"false",
]
def test_the_answer_survives_a_deep_object(self):
assert "-Depth 6" in self.script
def test_stops_on_errors_it_does_not_catch(self):
assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'")
def test_the_driver_carries_the_contract(self):
assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin)
+222
View File
@@ -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
+211
View File
@@ -0,0 +1,211 @@
"""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
+388
View File
@@ -0,0 +1,388 @@
"""Who can log in to a Windows host: local accounts, administrators, Remote Desktop
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_accounts_server_de.json (a German-language domain
member: "Administratoren", "Remotedesktopbenutzer", a domain group among the
administrators, Remote Desktop on, Guests denied it) and login_accounts_client.json (a
Windows 11 workgroup client, Remote Desktop off). What a real host emits the fixtures
cannot prove -- see the README there.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import login_accounts as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
MACHINE = "S-1-5-21-1004336348-1177238915-682003330"
DOMAIN = "S-1-5-21-3623811015-3361044348-30300820"
def _raw(name: str) -> dict[str, Any]:
return json.loads((FIXTURES / f"login_accounts_{name}.json").read_text())
class FakeTransport:
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(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("win01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_accounts()), host
def _by_name(reading: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {a["name"]: a for a in reading["accounts"]}
class TestGermanMemberServer:
def test_the_accounts_without_the_systems_own(self):
reading, _ = _read(_raw("server_de"))
assert [a["name"] for a in reading["accounts"]] == [
"Administrator",
"Gast",
"helpdesk",
"svc-backup",
]
def test_uid_is_the_rid_and_sid_the_whole_sid(self):
admin = _by_name(_read(_raw("server_de"))[0])["Administrator"]
assert admin["uid"] == 500
assert admin["sid"] == f"{MACHINE}-500"
assert admin["home"] == "C:\\Users\\Administrator"
assert admin["shell"] == ""
def test_the_last_login_is_the_account_databases(self):
reading, _ = _read(_raw("server_de"))
admin = _by_name(reading)["Administrator"]
assert admin["last_login"] == "2025-11-29T00:00:00+00:00"
assert admin["last_login_source"] == "sam"
assert admin["last_login_from"] is None
assert admin["last_login_port"] is None
assert reading["login_sources"] == ["sam"]
assert _by_name(reading)["Gast"]["last_login"] is None
assert _by_name(reading)["Gast"]["last_login_source"] is None
def test_administrators_are_found_by_sid_not_by_name(self):
"""The group is "Administratoren" here; S-1-5-32-544 finds it all the same."""
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["administrator"] is True
assert accounts["helpdesk"]["administrator"] is False
def test_remote_desktop_by_the_right_and_its_holders(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["remote_desktop"] is True
assert accounts["helpdesk"]["remote_desktop"] is True # Remotedesktopbenutzer
assert accounts["svc-backup"]["remote_desktop"] is False # no group holds it
def test_a_denied_group_wins_over_the_right(self):
raw = _raw("server_de")
raw["groups"][2]["members"].append(
{"path": "WinNT://CONTOSO/SRV01/helpdesk", "class": "User", "sid": f"{MACHINE}-1001"}
)
assert _by_name(_read(raw)[0])["helpdesk"]["remote_desktop"] is False
def test_denying_every_local_account_denies_them_all(self):
"""``Local account`` (S-1-5-113), as Microsoft's security baseline denies it."""
raw = _raw("server_de")
raw["rights"]["deny"].append("*S-1-5-113")
accounts = _by_name(_read(raw)[0])
assert not any(a["remote_desktop"] for a in accounts.values())
def test_a_right_given_to_everyone_reaches_every_account(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("*S-1-1-0")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_a_right_given_by_name_counts(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("svc-backup")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_locked_disabled_expired_or_locked_out(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Gast"]["locked"] is True # disabled
assert accounts["helpdesk"]["locked"] is True # locked out
assert accounts["svc-backup"]["locked"] is True # expired
assert accounts["Administrator"]["locked"] is False
def test_the_lock_out_not_read_is_none(self):
raw = _raw("server_de")
raw["users"][5]["account_expires"] = None
assert _by_name(_read(raw)[0])["svc-backup"]["locked"] is None
def test_password_and_account_expiry(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["password"] == "set"
assert accounts["Administrator"]["password_changed"] == "2025-05-15"
assert accounts["Administrator"]["password_expires"] == "never"
assert accounts["Administrator"]["account_expires"] == "never"
assert accounts["helpdesk"]["password_expires"] == "2025-10-22"
assert accounts["svc-backup"]["account_expires"] == "2025-11-26"
assert accounts["Gast"]["password"] is None
assert accounts["Gast"]["password_expires"] is None
def test_failed_attempts_since_the_last_login(self):
reading, _ = _read(_raw("server_de"))
accounts = _by_name(reading)
assert accounts["helpdesk"]["failed_logins"] == 7
assert accounts["svc-backup"]["failed_logins"] is None
assert accounts["helpdesk"]["failed_logins_capped"] is False
assert reading["failed_logins_source"] == "sam"
def test_read_as_an_administrator(self):
assert _read(_raw("server_de"))[0]["privileged"] is True
class TestTheGroups:
def test_the_groups_that_grant_administration_or_remote_desktop(self):
groups = _read(_raw("server_de"))[0]["groups"]
assert [(g["name"], g["sid"], g["grants"]) for g in groups] == [
("Administratoren", "S-1-5-32-544", ["administrator", "remote_desktop"]),
("Remotedesktopbenutzer", "S-1-5-32-555", ["remote_desktop"]),
]
def test_a_domain_group_among_the_administrators_by_name(self):
admins = _read(_raw("server_de"))[0]["groups"][0]["members"]
assert admins == [
{
"name": "SRV01\\Administrator",
"sid": f"{MACHINE}-500",
"local": True,
"group": False,
},
{
"name": "CONTOSO\\Domänen-Admins",
"sid": f"{DOMAIN}-512",
"local": False,
"group": True,
},
{"name": "CONTOSO\\jdoe", "sid": f"{DOMAIN}-1107", "local": False, "group": False},
{"name": f"{DOMAIN}-1290", "sid": f"{DOMAIN}-1290", "local": False, "group": False},
]
def test_a_principal_of_the_host_itself_is_local(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://NT-AUTORITÄT/INTERAKTIV", "class": "Group", "sid": "S-1-5-4"}
]
member = _read(raw)[0]["groups"][1]["members"][0]
assert member == {
"name": "NT-AUTORITÄT\\INTERAKTIV",
"sid": "S-1-5-4",
"local": True,
"group": True,
}
def test_without_a_sid_the_path_tells(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://CONTOSO/SRV01/old", "class": "", "sid": None},
{"path": "WinNT://CONTOSO/someone", "class": "User", "sid": None},
{"path": "", "class": "", "sid": None},
]
raw["users"] = []
members = _read(raw)[0]["groups"][1]["members"]
assert [(m["name"], m["local"], m["group"]) for m in members] == [
("SRV01\\old", True, None),
("CONTOSO\\someone", False, False),
("", None, None),
]
def test_a_domain_sid_without_the_hosts_own_is_told_by_its_path(self):
raw = _raw("server_de")
raw["users"] = []
admins = _read(raw)[0]["groups"][0]["members"]
assert [m["local"] for m in admins] == [True, False, False, None]
class TestWindows11Client:
def test_remote_desktop_off_lets_no_one_in(self):
reading, _ = _read(_raw("client"))
accounts = _by_name(reading)
assert {a["remote_desktop"] for a in accounts.values()} == {False}
assert [g["sid"] for g in reading["groups"]] == ["S-1-5-32-544"]
assert reading["groups"][0]["grants"] == ["administrator"]
def test_the_owner_is_an_administrator_the_other_user_is_not(self):
accounts = _by_name(_read(_raw("client"))[0])
assert accounts["alice"]["administrator"] is True
assert accounts["bob"]["administrator"] is False
def test_group_policy_wins_over_the_local_setting(self):
raw = _raw("client")
raw["rdp_deny_policy"] = "0"
accounts = _by_name(_read(raw)[0])
assert accounts["alice"]["remote_desktop"] is True
assert accounts["bob"]["remote_desktop"] is False
class TestNotRead:
def test_rights_not_read_leave_remote_desktop_unknown(self):
raw = _raw("server_de")
raw["rights"] = None
raw["admin"] = False
reading, _ = _read(raw)
assert {a["remote_desktop"] for a in reading["accounts"]} == {None}
assert [g["grants"] for g in reading["groups"]] == [["administrator"]]
assert reading["privileged"] is False
def test_the_remote_desktop_setting_not_read_is_unknown(self):
raw = _raw("server_de")
raw["rdp_deny"] = None
assert {a["remote_desktop"] for a in _read(raw)[0]["accounts"]} == {None}
def test_administrators_not_read_is_unknown(self, caplog):
raw = _raw("server_de")
raw["groups"] = [g for g in raw["groups"] if g["sid"] != "S-1-5-32-544"]
raw["errors"] = ["group S-1-5-32-544: Zugriff verweigert"]
with caplog.at_level("INFO"):
reading, _ = _read(raw)
assert {a["administrator"] for a in reading["accounts"]} == {None}
assert "Zugriff verweigert" in caplog.text
def test_no_failed_attempts_read_has_no_source(self):
raw = _raw("server_de")
for user in raw["users"]:
user["bad_passwords"] = None
assert _read(raw)[0]["failed_logins_source"] is None
def test_one_group_member_arrives_as_an_object(self):
"""ConvertTo-Json writes a one-element array as its element."""
raw = _raw("server_de")
raw["groups"][1]["members"] = raw["groups"][1]["members"][0]
raw["users"] = raw["users"][0]
reading, _ = _read(raw)
assert [a["name"] for a in reading["accounts"]] == ["Administrator"]
assert len(reading["groups"][1]["members"]) == 1
def test_without_get_localuser_the_reading_is_not_supported(self):
raw = _raw("server_de")
raw["users"] = None
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
_read(raw)
@pytest.mark.parametrize("answer", ["", "[]", "null"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
def test_an_account_without_a_sid_is_left_out(self):
raw = _raw("server_de")
raw["users"].append({"name": "odd", "sid": None})
raw["users"].append("garbage")
assert "odd" not in _by_name(_read(raw)[0])
class TestDomainController:
def test_its_accounts_are_the_directorys_its_groups_are_read(self):
raw = copy.deepcopy(_raw("server_de"))
raw.update(domain_role=5, users=[])
reading, _ = _read(raw)
assert reading["accounts"] == []
assert reading["login_sources"] == []
assert reading["failed_logins_source"] is None
assert reading["groups"][0]["sid"] == "S-1-5-32-544"
def test_a_domain_controller_without_get_localuser_is_read_all_the_same(self):
raw = _raw("server_de")
raw.update(domain_role=4, users=None)
assert _read(raw)[0]["accounts"] == []
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw("server_de"))
assert host.sent == [mod._PS_LOGIN_ACCOUNTS]
def test_the_conventions(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "$ErrorActionPreference = 'Stop'" in script
assert "Get-Command -Name Get-LocalUser" in script
assert "ToUnixTimeMilliseconds" in script
assert "ConvertTo-Json -Compress -Depth 6" in script
def test_groups_are_named_by_sid_never_by_their_english_name(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "'S-1-5-32-544'" in script and "'S-1-5-32-555'" in script
assert "Translate([Security.Principal.NTAccount])" in script
assert "WinNT://' + $env:COMPUTERNAME + '/Administrators" not in script
def test_it_reads_no_secret_and_leaves_nothing_behind(self):
"""The only file is secedit's export of the user rights, removed in ``finally``."""
script = mod._PS_LOGIN_ACCOUNTS
assert "/areas USER_RIGHTS" in script
assert "finally { Remove-Item -LiteralPath $cfg" in script
for verb in (
"Set-LocalUser",
"Add-LocalGroupMember",
"net user",
"SetPassword",
"/configure",
):
assert verb not in script
def test_a_native_command_runs_inside_cmd_with_stderr_merged(self):
"""A line on stderr would be an error record in a remote session (time_sync.py)."""
assert "cmd.exe /c ('secedit " in mod._PS_LOGIN_ACCOUNTS
assert "' 2>&1')" in mod._PS_LOGIN_ACCOUNTS
+290
View File
@@ -0,0 +1,290 @@
"""The logins a Windows host recorded: console and Remote Desktop, from the Security log
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_sessions.json: a domain member with a Remote Desktop logon
of an administrator (two linked events), its window manager's and font driver's logons, a
local console logon, a cached one, one over IPv6 and one from the reading's own address.
What a real host emits the fixtures cannot prove -- see the README there.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import LoginSessionsUnavailable
from napalm_windows import WindowsDriver
from napalm_windows import login_sessions as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "login_sessions.json"
def _raw() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
class FakeTransport:
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(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("srv01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_sessions()), host
class TestTheSessions:
def test_console_and_remote_desktop_newest_first(self):
reading, _ = _read(_raw())
assert [(s["user"], s["tty"], s["address"]) for s in reading["sessions"]] == [
("helpdesk", "rdp", "2001:db8::10"),
("CONTOSO\\jdoe", "rdp", "192.0.2.10"),
("Administrator", "console", None),
("CONTOSO\\jdoe", "console", None),
]
def test_an_administrators_two_linked_logons_are_one_session(self):
rdp = _read(_raw())[0]["sessions"][1]
assert rdp == {
"user": "CONTOSO\\jdoe",
"tty": "rdp",
"address": "192.0.2.10",
"started": "2025-11-30T19:00:00+00:00",
"ended": "2025-11-30T21:00:00+00:00",
}
def test_the_window_manager_and_font_driver_are_no_one(self):
users = {s["user"] for s in _read(_raw())[0]["sessions"]}
assert not {"DWM-2", "UMFD-2"} & {u.split("\\")[-1] for u in users}
def test_the_hosts_own_accounts_go_by_name_alone(self):
users = [s["user"] for s in _read(_raw())[0]["sessions"]]
assert "Administrator" in users and "SRV01\\Administrator" not in users
def test_a_console_logon_ended_by_its_logoff(self):
console = _read(_raw())[0]["sessions"][2]
assert console["started"] == "2025-11-29T22:00:00+00:00"
assert console["ended"] == "2025-11-29T23:00:00+00:00"
def test_a_logon_still_running_has_no_end(self):
assert _read(_raw())[0]["sessions"][3]["ended"] is None
def test_a_logoff_before_the_logon_is_an_earlier_boots(self):
"""A logon ID is used again after a restart."""
assert _read(_raw())[0]["sessions"][0]["ended"] is None
def test_a_network_logon_or_an_unlock_is_not_a_session(self):
raw = _raw()
for kind in ("3", "7"):
raw["logons"].append(
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "SRV01",
"id": f"5{kind}",
"type": kind,
"ip": "192.0.2.99",
"linked": "0",
}
)
assert all(s["user"] != "x" for s in _read(raw)[0]["sessions"])
def test_an_entra_id_account_is_a_person(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-12-1-111-222-333-444",
"user": "alice@contoso.com",
"domain": "AzureAD",
"id": "77",
"type": "2",
"ip": "-",
"linked": None,
}
]
assert [s["user"] for s in _read(raw)[0]["sessions"]] == ["AzureAD\\alice@contoso.com"]
def test_an_event_without_an_id_or_a_time_is_skipped(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "",
"type": "2",
"ip": "-",
"linked": "0",
},
{
"t": None,
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "-",
"linked": "0",
},
"garbage",
]
raw["ends"] = [{"t": None, "id": "9"}, {"t": 1, "id": None}]
assert _read(raw)[0]["sessions"] == []
def test_a_remote_desktop_logon_from_the_loopback_keeps_it(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "8",
"type": "10",
"ip": "127.0.0.1",
"linked": "0",
},
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "workstation-7",
"linked": "0",
},
]
sessions = {s["user"]: s["address"] for s in _read(raw)[0]["sessions"]}
assert sessions == {"x": "127.0.0.1", "y": "workstation-7"}
def test_the_cap(self, monkeypatch):
monkeypatch.setattr(mod, "SESSIONS_READ", 2)
assert len(_read(_raw())[0]["sessions"]) == 2
class TestOwnAddress:
def test_the_readings_own_winrm_logon_names_it(self):
reading, _ = _read(_raw())
assert reading["own_address"] == "198.51.100.2"
def test_its_remote_desktop_sessions_are_left_out(self):
reading, _ = _read(_raw())
assert all(s["address"] != "198.51.100.2" for s in reading["sessions"])
def test_without_an_address_on_its_logon_the_one_winrm_client(self):
raw = _raw()
raw.update(own_ip="-", winrm_peers=["::ffff:198.51.100.2"])
assert _read(raw)[0]["own_address"] == "198.51.100.2"
def test_several_winrm_clients_name_none(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers=["198.51.100.2", "198.51.100.3"])
reading, _ = _read(raw)
assert reading["own_address"] is None
assert len(reading["sessions"]) == 5
def test_one_winrm_client_arrives_as_a_string(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers="198.51.100.4")
assert _read(raw)[0]["own_address"] == "198.51.100.4"
class TestCoverage:
def test_the_oldest_event_the_log_holds(self):
assert _read(_raw())[0]["records_since"] == "2025-11-28T00:00:00+00:00"
def test_an_empty_log_has_none(self):
raw = _raw()
raw["oldest"] = None
assert _read(raw)[0]["records_since"] is None
def test_no_logon_not_even_its_own_is_no_audit(self):
raw = _raw()
raw.update(canary=False, logons=[])
with pytest.raises(LoginSessionsUnavailable, match="not audited"):
_read(raw)
def test_its_own_logon_not_found_with_others_is_read(self):
raw = _raw()
raw["canary"] = False
reading, _ = _read(raw)
assert reading["own_address"] == "198.51.100.2" # the one WinRM client
assert len(reading["sessions"]) == 4
def test_no_logon_while_its_own_was_not_looked_for_is_nobody(self):
raw = _raw()
raw.update(canary=None, logons=[])
assert _read(raw)[0]["sessions"] == []
@pytest.mark.parametrize("answer", ["", "[]"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw())
assert host.sent == [mod._PS_LOGIN_SESSIONS]
def test_no_match_is_none_not_an_error(self):
assert "NoMatchingEventsFound" in mod._PS_LOGIN_SESSIONS
def test_the_window_is_bounded_on_the_host(self):
script = mod._PS_LOGIN_SESSIONS
assert "timediff(@SystemTime) <= 604800000" in script
assert "-MaxEvents $max" in script
assert "__" not in script
def test_only_console_remote_desktop_and_cached_logons(self):
script = mod._PS_LOGIN_SESSIONS
assert "$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)" in script
assert "Logon 3" not in script and "Logon 7" not in script
def test_the_conventions(self):
script = mod._PS_LOGIN_SESSIONS
assert "$ErrorActionPreference = 'Stop'" in script
assert "ToUnixTimeMilliseconds" in script
assert "Clear-EventLog" not in script and "wevtutil" not in script
+103
View File
@@ -0,0 +1,103 @@
"""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
+123
View File
@@ -0,0 +1,123 @@
"""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() == []
+330
View File
@@ -0,0 +1,330 @@
"""A Windows host's security posture as napalm-device-types' hardening reading (NetOrk/netork#2893).
The reading is one script whose JSON a fake host answers, from
tests/fixtures/synthetic/posture_client.json (a Windows 11 client with everything on) and
posture_server.json (a Windows Server VM booted from BIOS, without the BitLocker feature,
Defender passive beside another product, the Private profile off).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import posture as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
LINUX_KEYS = (
"lsm",
"selinux",
"apparmor",
"crypto_policy",
"fips",
"cpu_vulnerabilities",
"cmdline",
"mitigations",
"nosmt",
"os_ids",
"virtualization",
"cpu_vendor",
)
def _fixture(name: str) -> dict[str, Any]:
data: dict[str, Any] = json.loads((FIXTURES / f"posture_{name}.json").read_text())
return data
class FakeHost:
is_open = True
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def close(self) -> None:
self.is_open = False
def _read(raw: dict[str, Any] | str) -> dict[str, Any]:
host = FakeHost(raw if isinstance(raw, str) else json.dumps(raw))
driver = WindowsDriver("win01", "admin", "secret")
driver._transport = host # type: ignore[assignment]
reading: dict[str, Any] = dict(driver.get_hardening())
assert host.sent == [mod._PS_POSTURE]
return reading
def _with(name: str, **changes: Any) -> dict[str, Any]:
return {**_fixture(name), **changes}
class TestClient:
def test_everything_on(self):
reading = _read(_fixture("client"))
assert reading["secure_boot"] == "on"
assert reading["tpm"] == {
"present": True,
"enabled": True,
"activated": True,
"owned": True,
"version": "2.0",
"manufacturer": "INTC",
}
assert reading["disk_encryption"] == {
"provider": "bitlocker",
"installed": True,
"volumes": [
{
"volume": "C:",
"system": True,
"protection": "on",
"status": "fully_encrypted",
"method": "xts_aes_128",
},
{
"volume": "D:",
"system": False,
"protection": "off",
"status": "fully_decrypted",
"method": None,
},
],
}
assert reading["antimalware"] == {
"product": "Microsoft Defender Antivirus",
"enabled": True,
"real_time": True,
"mode": "active",
"signatures_updated": 1764547200,
"signature_age_days": 0,
"signature_version": "1.443.512.0",
"tamper_protected": True,
}
assert reading["firewall_profiles"] == [
{"name": "domain", "enabled": True},
{"name": "private", "enabled": True},
{"name": "public", "enabled": True},
]
assert reading["vbs"] == {"status": "running", "running": ["credential_guard", "hvci"]}
def test_what_only_linux_has_is_not_read(self):
reading = _read(_fixture("client"))
assert all(reading[key] is None for key in LINUX_KEYS)
class TestServer:
def test_a_bios_boot_has_no_secure_boot_to_switch_on(self):
assert _read(_fixture("server"))["secure_boot"] == "unsupported"
def test_no_tpm(self):
assert _read(_fixture("server"))["tpm"] == {
"present": False,
"enabled": None,
"activated": None,
"owned": None,
"version": None,
"manufacturer": None,
}
def test_bitlocker_not_installed_is_said_so_not_an_error(self):
assert _read(_fixture("server"))["disk_encryption"] == {
"provider": "bitlocker",
"installed": False,
"volumes": [],
}
def test_defender_passive_beside_another_product(self):
antimalware = _read(_fixture("server"))["antimalware"]
assert antimalware["mode"] == "passive"
assert antimalware["real_time"] is False
assert antimalware["signature_age_days"] == 7
def test_a_profile_switched_off(self):
profiles = _read(_fixture("server"))["firewall_profiles"]
assert {"name": "private", "enabled": False} in profiles
def test_vbs_off_runs_nothing(self):
assert _read(_fixture("server"))["vbs"] == {"status": "off", "running": []}
class TestEachPartOnItsOwn:
@pytest.mark.parametrize(
("part", "key"),
[
("secure_boot", "secure_boot"),
("tpm", "tpm"),
("bitlocker", "disk_encryption"),
("defender", "antimalware"),
("firewall", "firewall_profiles"),
("vbs", "vbs"),
],
)
def test_a_part_that_failed_is_not_read_and_the_rest_is(self, part, key):
raw = _with("client", **{part: None, "errors": {part: "Access denied"}})
reading = _read(raw)
assert reading[key] is None
others = {"secure_boot", "tpm", "disk_encryption", "antimalware", "firewall_profiles"}
assert all(reading[k] is not None for k in others - {key})
def test_a_cmdlet_the_host_lacks_is_not_read(self):
"""Server Core without Defender, a build without the firewall module."""
reading = _read(_with("client", defender=None, firewall=None, secure_boot=None))
assert reading["antimalware"] is None
assert reading["firewall_profiles"] is None
assert reading["secure_boot"] is None
def test_secure_boot_off(self):
assert _read(_with("client", secure_boot="False"))["secure_boot"] == "off"
def test_a_secure_boot_answer_it_does_not_know_is_not_read(self):
assert _read(_with("client", secure_boot="maybe"))["secure_boot"] is None
class TestValues:
def test_one_element_lists_arrive_bare(self):
"""ConvertTo-Json unwraps a one-element array into its element."""
raw = _fixture("client")
raw["bitlocker"]["volumes"] = raw["bitlocker"]["volumes"][0]
raw["firewall"] = raw["firewall"][0]
raw["vbs"]["running"] = "2"
reading = _read(raw)
assert [v["volume"] for v in reading["disk_encryption"]["volumes"]] == ["C:"]
assert reading["firewall_profiles"] == [{"name": "domain", "enabled": True}]
assert reading["vbs"]["running"] == ["hvci"]
@pytest.mark.parametrize(
("mode", "word"),
[
("Normal", "active"),
("Passive Mode", "passive"),
("Passive", "passive"),
("EDR Block Mode", "edr_block"),
("SxS Passive Mode", "sxs_passive"),
("Not running", None),
(None, None),
],
)
def test_defenders_running_mode(self, mode, word):
raw = _fixture("client")
raw["defender"]["running_mode"] = mode
assert _read(raw)["antimalware"]["mode"] == word
def test_defender_with_its_service_off_scans_nothing(self):
raw = _fixture("client")
raw["defender"].update(am_service=False)
antimalware = _read(raw)["antimalware"]
assert antimalware["enabled"] is False
def test_defender_without_signatures_yet(self):
raw = _fixture("client")
raw["defender"].update(signature_updated=None, signature_age=None, signature_version="")
antimalware = _read(raw)["antimalware"]
assert antimalware["signatures_updated"] is None
assert antimalware["signature_age_days"] is None
assert antimalware["signature_version"] is None
def test_the_os_volume_is_the_system_volume_by_its_type_or_its_letter(self):
raw = _fixture("client")
raw["bitlocker"]["volumes"] = [
{
"drive": "C:",
"volume_type": "1",
"protection": "2",
"conversion": "4",
"method": "7",
},
{
"drive": "E:",
"volume_type": "0",
"protection": "0",
"conversion": "2",
"method": "4",
},
{
"drive": None,
"volume_type": "1",
"protection": "0",
"conversion": "0",
"method": "0",
},
]
volumes = _read(raw)["disk_encryption"]["volumes"]
assert [(v["volume"], v["system"]) for v in volumes] == [("C:", True), ("E:", True)]
assert volumes[0]["protection"] == "unknown"
assert volumes[0]["status"] == "encryption_paused"
assert volumes[0]["method"] == "xts_aes_256"
assert volumes[1]["status"] == "encrypting"
assert volumes[1]["method"] == "aes_256"
def test_numbers_it_does_not_know_are_not_guessed(self):
raw = _fixture("client")
raw["bitlocker"]["volumes"] = [
{"drive": "C:", "volume_type": "0", "protection": "9", "conversion": "9", "method": "x"}
]
raw["vbs"] = {"status": "7", "running": ["9"]}
raw["tpm"]["spec_version"] = ""
reading = _read(raw)
volume = reading["disk_encryption"]["volumes"][0]
assert (volume["protection"], volume["status"], volume["method"]) == ("unknown", None, None)
assert reading["vbs"] == {"status": None, "running": ["service_9"]}
assert reading["tpm"]["version"] is None
def test_a_firewall_profile_not_configured_is_not_read(self):
raw = _with("client", firewall=[{"name": "Public", "enabled": "NotConfigured"}])
assert _read(raw)["firewall_profiles"] == [{"name": "public", "enabled": None}]
def test_an_empty_answer_raises(self):
with pytest.raises(ValueError, match="came back empty"):
_read("")
class TestTheScript:
def test_it_never_touches_a_key(self):
"""Get-BitLockerVolume returns the key protectors, recovery passwords among them;
the CIM class's properties carry none."""
for word in ("Get-BitLockerVolume", "KeyProtector", "RecoveryPassword", "manage-bde"):
assert word not in mod._PS_POSTURE
def test_it_changes_nothing(self):
for verb in ("Set-", "Enable-", "Disable-", "Update-MpSignature", "Start-MpScan"):
assert verb not in mod._PS_POSTURE
def test_it_probes_the_cmdlets_first(self):
for cmdlet in ("Confirm-SecureBootUEFI", "Get-MpComputerStatus", "Get-NetFirewallProfile"):
assert f"Has '{cmdlet}'" in mod._PS_POSTURE
def test_it_stops_on_errors_and_catches_each_part(self):
assert "$ErrorActionPreference = 'Stop'" in mod._PS_POSTURE
assert mod._PS_POSTURE.count("catch") >= 6
def test_the_driver_reads_the_hardening():
assert callable(getattr(WindowsDriver, "get_hardening", None))
+125
View File
@@ -0,0 +1,125 @@
"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889).
One script reads both; a fake transport answers it from
tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command
line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the
owner. The fixture holds the cases the join decides:
* 0, the System Idle Process: no process, left out as ``ps`` leaves it out;
* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled;
* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID
that was reused between the two reads, dropped;
* 7777, started after ``Win32_Process`` was read: not part of the reading.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import processes as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _reading() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
return d
def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]:
return {p["pid"]: p for p in _driver(reading).get_processes()}
def test_the_join_keeps_the_processes_both_reads_saw():
assert sorted(_by_pid()) == [4, 812, 4312]
def test_a_process_reads_like_ps():
assert _by_pid()[4312] == {
"pid": 4312,
"ppid": 3988,
"user": "WIN01\\admin",
# 120 CPU seconds in 600 s on 4 logical processors
"cpu": 5.0,
# 100 MiB of 8 GiB
"memory": 1.2,
"vsz": 2203500000000 // 1024,
"rss": 102400,
"tty": "",
"state": "",
# 11:50 UTC, an hour east of it
"started": "Mon Dec 1 12:50:00 2025",
"command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo',
}
def test_a_process_without_a_command_line_shows_its_name():
system = _by_pid()[4]
assert system["command"] == "System"
assert system["started"] == ""
assert system["cpu"] == 0.0
def test_a_start_one_second_apart_is_the_same_process():
# Get-Process and CIM round the start differently.
reading = _reading()
reading["owners"][2]["started"] += 1
assert 812 in _by_pid(reading)
def test_without_elevation_the_owner_is_unknown():
# Get-Process -IncludeUserName needs an elevated session; the script falls back.
reading = _reading()
for owner in reading["owners"]:
owner.pop("user")
assert {p["user"] for p in _by_pid(reading).values()} == {""}
def test_cpu_stays_within_a_hundred_percent():
reading = _reading()
reading["processes"][3]["cpu"] = 10**13
assert _by_pid(reading)[4312]["cpu"] == 100.0
def test_a_single_process_survives_powershells_unwrapping():
reading = _reading()
reading["processes"] = reading["processes"][2]
reading["owners"] = reading["owners"][2]
assert sorted(_by_pid(reading)) == [812]
def test_one_script_reads_both_sources():
d = _driver()
d.get_processes()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_PROCESSES
assert "Win32_Process" in script
assert "Get-Process -IncludeUserName" in script
def test_an_empty_answer_is_no_reading():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport("")
with pytest.raises(ValueError):
d.get_processes()
+326
View File
@@ -0,0 +1,326 @@
"""Repair runs on Windows: SFC, DISM and Microsoft Defender over PowerShell Remoting (NetOrk/netork#2899).
A fake transport replays what a run's script emits, one output object per line of
tests/fixtures/synthetic/<run>.txt, through ``run_streaming``; the scripts end with a
``napalm-exit-code:`` line, or say ``napalm-not-available:`` where the tool is missing.
The fixtures are written from Microsoft's documented output, not recorded from a host.
"""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
import pytest
from napalm.base.exceptions import ConnectionClosedException
from napalm_device_types import HostRepairMixin, offered_host_repairs
from napalm_windows import WindowsDriver
from napalm_windows import repairs as mod
from napalm_windows.transport import PowerShellError
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
def _fixture(name: str) -> list[str]:
return (FIXTURES / name).read_text().split("\n")[:-1]
class FakeTransport:
"""Replays *items* as the output objects of the next streamed script."""
def __init__(self, items: list[str], *, error: Exception | None = None) -> None:
self.items = items
self.error = error
self.scripts: list[str] = []
self.limits: list[float] = []
self.is_open = True
def run_streaming(
self, script: str, on_output: Callable[[str], None], *, limit: float
) -> list[str]:
self.scripts.append(script)
self.limits.append(limit)
for item in self.items:
on_output(item)
if self.error is not None:
raise self.error
return list(self.items)
def close(self) -> None:
self.is_open = False
def _driver(items: list[str], **kwargs) -> tuple[WindowsDriver, FakeTransport]:
transport = FakeTransport(items, **kwargs)
driver = WindowsDriver("win01", "admin", "secret")
driver._transport = transport # type: ignore[assignment]
return driver, transport
class TestCatalog:
def test_the_driver_carries_the_contract(self):
assert issubclass(WindowsDriver, HostRepairMixin)
def test_offers_the_checks_and_the_antimalware_runs_not_the_repairs(self):
# sfc /scannow and DISM /RestoreHealth wait for a real-host test (#2899).
assert offered_host_repairs(WindowsDriver) == [
"verify_system_files",
"check_component_store",
"update_antimalware_signatures",
"scan_antimalware",
]
class TestToolLines:
def test_an_object_is_one_line(self):
assert mod.tool_lines("Verification 52% complete.") == ["Verification 52% complete."]
def test_utf16_text_read_as_bytes_loses_its_nuls(self):
# sfc writes UTF-16 to a redirected stdout; decoded byte by byte, each
# character is followed by a NUL.
raw = "Windows Resource Protection".encode("utf-16-le").decode("latin-1")
assert "\x00" in raw
assert mod.tool_lines(raw) == ["Windows Resource Protection"]
def test_a_byte_order_mark_is_dropped(self):
assert mod.tool_lines("Beginning system scan.") == ["Beginning system scan."]
def test_carriage_returns_split_progress_into_lines(self):
assert mod.tool_lines("Verification 1% complete.\rVerification 2% complete.\r\n") == [
"Verification 1% complete.",
"Verification 2% complete.",
]
def test_blank_lines_and_trailing_spaces_go(self):
assert mod.tool_lines(" \r\n\nresult ") == ["result"]
class TestVerifySystemFiles:
def test_streams_the_lines_and_succeeds_on_exit_code_zero(self):
driver, transport = _driver(_fixture("sfc_verifyonly.txt"))
seen: list[str] = []
result = driver.verify_system_files(log=seen.append)
assert result["success"] is True
assert result["exit_code"] == 0
assert seen[0] == "Beginning system scan. This process will take some time."
assert seen[-1] == "Windows Resource Protection did not find any integrity violations."
assert not any(line.startswith("napalm-") for line in seen)
assert result["output"] == "\n".join(seen)
def test_runs_sfc_verifyonly_decoded_as_utf16(self):
driver, transport = _driver(_fixture("sfc_verifyonly.txt"))
driver.verify_system_files()
script = transport.scripts[0]
assert "'/verifyonly'" in script
assert "System32\\sfc.exe" in script
assert "[System.Text.Encoding]::Unicode" in script
assert "/scannow" not in script
assert transport.limits == [mod.SFC_LIMIT]
def test_utf16_output_with_nuls_reads_as_text(self):
items = [
line.encode("utf-16-le").decode("latin-1")
for line in _fixture("sfc_verifyonly.txt")[:-1]
] + ["napalm-exit-code:0"]
driver, _ = _driver(items)
result = driver.verify_system_files()
assert "did not find any integrity violations" in result["output"]
assert "\x00" not in result["output"]
def test_a_non_zero_exit_code_fails_with_the_last_lines(self):
items = [
"Beginning system scan. This process will take some time.",
"Windows Resource Protection could not start the repair service.",
"napalm-exit-code:1",
]
driver, _ = _driver(items)
result = driver.verify_system_files()
assert result["success"] is False
assert result["exit_code"] == 1
assert result["error"].endswith("could not start the repair service.")
def test_a_missing_tool_is_not_available_not_an_error(self):
driver, _ = _driver(["napalm-not-available:sfc.exe"])
result = driver.verify_system_files()
assert result == {
"success": False,
"output": "",
"exit_code": None,
"error": "sfc.exe is not available on this host",
}
def test_without_log_it_still_returns_the_output(self):
driver, _ = _driver(_fixture("sfc_verifyonly.txt"))
assert "Verification 100% complete." in driver.verify_system_files()["output"]
class TestCheckComponentStore:
def test_scans_health_in_english_and_succeeds(self):
driver, transport = _driver(_fixture("dism_scanhealth.txt"))
seen: list[str] = []
result = driver.check_component_store(log=seen.append)
assert result["success"] is True
assert "No component store corruption detected." in seen[-2]
script = transport.scripts[0]
assert "System32\\Dism.exe" in script
assert "'/Online /Cleanup-Image /ScanHealth /English'" in script
assert "RestoreHealth" not in script
assert transport.limits == [mod.DISM_LIMIT]
def test_an_hresult_exit_code_fails_in_hex(self):
driver, _ = _driver(_fixture("dism_scanhealth_failed.txt"))
result = driver.check_component_store()
assert result["success"] is False
assert result["exit_code"] == 0x800F081F
assert result["error"].startswith("DISM /ScanHealth ended with exit code 0x800F081F:")
assert "dism.log" in result["error"]
class TestAntimalwareSignatures:
def test_updates_and_reports_the_versions(self):
driver, transport = _driver(_fixture("defender_signature_update.txt"))
seen: list[str] = []
result = driver.update_antimalware_signatures(log=seen.append)
assert result["success"] is True
assert seen == [
"Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
"Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC",
]
script = transport.scripts[0]
assert "Update-MpSignature" in script
assert "Get-Command -Name Update-MpSignature" in script
assert transport.limits == [mod.SIGNATURE_LIMIT]
def test_a_host_without_defender_says_so(self):
driver, _ = _driver(["napalm-not-available:Microsoft Defender Antivirus"])
result = driver.update_antimalware_signatures()
assert result["success"] is False
assert result["error"] == "Microsoft Defender Antivirus is not available on this host"
def test_a_refused_update_fails_with_its_reason(self):
items = [
"Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
"Update-MpSignature failed: Virus and spyware definitions update was completed with errors.",
"Signatures after: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
"napalm-exit-code:1",
]
driver, _ = _driver(items)
result = driver.update_antimalware_signatures()
assert result["success"] is False
assert "completed with errors" in result["error"]
class TestScanAntimalware:
def test_a_quick_scan_reports_what_it_found(self):
driver, transport = _driver(_fixture("defender_quick_scan.txt"))
seen: list[str] = []
result = driver.scan_antimalware(log=seen.append)
assert result["success"] is True
assert "Threats detected: 1" in seen
script = transport.scripts[0]
assert "Start-MpScan -ScanType QuickScan" in script
assert transport.limits == [mod.QUICK_SCAN_LIMIT]
def test_a_full_scan_has_its_own_limit(self):
driver, transport = _driver(["napalm-exit-code:0"])
driver.scan_antimalware(quick=False)
assert "Start-MpScan -ScanType FullScan" in transport.scripts[0]
assert transport.limits == [mod.FULL_SCAN_LIMIT]
class TestLimit:
@pytest.mark.parametrize(
("run", "bound"),
[
(lambda d, **kw: d.verify_system_files(**kw), mod.SFC_LIMIT),
(lambda d, **kw: d.check_component_store(**kw), mod.DISM_LIMIT),
(lambda d, **kw: d.update_antimalware_signatures(**kw), mod.SIGNATURE_LIMIT),
(lambda d, **kw: d.scan_antimalware(**kw), mod.QUICK_SCAN_LIMIT),
(lambda d, **kw: d.scan_antimalware(False, **kw), mod.FULL_SCAN_LIMIT),
],
)
def test_a_callers_limit_tightens_the_bound_never_widens_it(self, run, bound):
driver, transport = _driver(["napalm-exit-code:0"])
run(driver, limit=600)
run(driver, limit=bound * 2)
run(driver)
assert transport.limits == [600, bound, bound]
class TestCutOff:
def test_a_run_past_its_limit_fails_with_what_it_printed(self):
driver, _ = _driver(
["Beginning system scan.", "Verification 40% complete."],
error=TimeoutError("The script did not end within 3600 seconds"),
)
result = driver.verify_system_files()
assert result["success"] is False
assert result["exit_code"] is None
assert result["error"].startswith("sfc /verifyonly ended without an exit code:")
assert "Verification 40% complete." in result["error"]
assert result["error"].endswith("did not end within 3600 seconds")
def test_an_error_the_script_wrote_fails_the_run(self):
driver, _ = _driver([], error=PowerShellError("Access is denied."))
result = driver.check_component_store()
assert result["success"] is False
assert result["error"].endswith("Access is denied.")
def test_an_unreadable_exit_code_is_none(self):
driver, _ = _driver(["done", "napalm-exit-code:"])
assert driver.verify_system_files()["exit_code"] is None
def test_a_closed_connection_raises(self):
driver = WindowsDriver("win01", "admin", "secret")
with pytest.raises(ConnectionClosedException):
driver.verify_system_files()
@pytest.mark.parametrize(
"script",
[
mod._PS_SFC_VERIFY,
mod._PS_DISM_SCAN,
mod._PS_SIGNATURE_UPDATE,
mod._PS_QUICK_SCAN,
mod._PS_FULL_SCAN,
],
)
def test_every_script_follows_the_conventions(script):
assert "$ErrorActionPreference = 'Stop'" in script
assert "napalm-exit-code:" in script
assert "napalm-not-available:" in script
# No restart and no restore point as a side effect of a run (#2899).
for forbidden in ("Restart-Computer", "Checkpoint-Computer", "shutdown"):
assert forbidden not in script
+652
View File
@@ -0,0 +1,652 @@
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
The reading is one script whose JSON a fake transport answers from
tests/fixtures/synthetic/scheduled_tasks.json; every write is one script, read
here as text. What a real host does with those scripts the fixtures cannot
prove -- see the README there.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import (
ScheduledJobChanged,
ScheduledJobRefused,
ScheduledJobsMixin,
job_digest,
)
from napalm_windows import WindowsDriver, task_xml
from napalm_windows import scheduled_tasks as mod
from napalm_windows.time_zones import iana_time_zone
from napalm_windows.transport import PowerShellError
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "scheduled_tasks.json"
DEFRAG = "task:\\Microsoft\\Windows\\Defrag\\ScheduledDefrag"
REBOOT = "task:\\Microsoft\\Windows\\UpdateOrchestrator\\Reboot"
BACKUP = "task:\\Admin's backup"
DUMP = "task:\\nightly-dump"
UPDATER = "task:\\Vendor\\Updater"
def _reading() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
class FakeTransport:
"""Answers the reading script with *reading*; records every other script."""
def __init__(self, reading: Any, fail: str | None = None):
self.reading = reading
self.fail = fail
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
if script == mod._PS_SCHEDULED_TASKS:
return self.reading if isinstance(self.reading, str) else json.dumps(self.reading)
if self.fail:
raise PowerShellError(self.fail)
return ""
def close(self) -> None:
self.is_open = False
@property
def writes(self) -> list[str]:
return [s for s in self.sent if s != mod._PS_SCHEDULED_TASKS]
def _driver(reading: Any = None, fail: str | None = None) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(_reading() if reading is None else reading, fail) # type: ignore[assignment]
return d
def _jobs(reading: Any = None) -> dict[str, dict[str, Any]]:
return {j["key"]: dict(j) for j in _driver(reading).get_scheduled_jobs()["jobs"]}
def _digest(key: str, reading: Any = None) -> str:
return str(_jobs(reading)[key]["digest"])
def _spec(**changes: Any) -> dict[str, Any]:
spec = {
"name": "nightly-dump",
"schedule": "30 2 * * *",
"run_as": "backup",
"command": "pg_dump -f D:\\dump.sql app",
"enabled": True,
"description": "Dump the database",
}
spec.update(changes)
return spec
def _without_dump() -> dict[str, Any]:
reading = _reading()
reading["tasks"] = [t for t in reading["tasks"] if t["name"] != "nightly-dump"]
reading["count"] = len(reading["tasks"])
return reading
# ---------------------------------------------------------------------------
# The contract
# ---------------------------------------------------------------------------
def test_a_windows_host_offers_every_verb():
assert issubclass(WindowsDriver, ScheduledJobsMixin)
for verb in (
"get_scheduled_jobs",
"manage_scheduled_job",
"put_scheduled_job",
"delete_scheduled_job",
):
assert callable(getattr(WindowsDriver, verb))
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
class TestReading:
def test_every_task_in_one_round_trip(self):
d = _driver()
reading = d.get_scheduled_jobs()
assert len(reading["jobs"]) == 5
assert d._transport.sent == [mod._PS_SCHEDULED_TASKS]
def test_the_script_joins_the_task_and_its_run_info_and_changes_nothing(self):
script = mod._PS_SCHEDULED_TASKS
assert "Get-ScheduledTask" in script
assert "Get-ScheduledTaskInfo" in script
assert "ConvertTo-Json" in script
for verb in ("Set-", "Register-", "Unregister-", "Enable-", "Disable-", "Start-"):
assert verb not in script
def test_a_platform_task(self):
job = _jobs()[DEFRAG]
assert {k: job[k] for k in job if k != "digest"} == {
"key": DEFRAG,
"kind": "task",
"source": "\\Microsoft\\Windows\\Defrag\\ScheduledDefrag",
"run_as": "SYSTEM",
"schedule": "weekly on Sun at 01:00",
"schedule_kind": "triggers",
"command": "%windir%\\system32\\defrag.exe -c -h -o -$",
"enabled": True,
"managed_by": "platform",
"actions": ["enable", "disable", "run"],
"description": "This task optimizes local storage drives.",
"last_run": "2026-11-01T00:00:12+00:00",
"last_result": "success",
"next_run": "2026-11-08T00:00:00+00:00",
}
def test_the_digest_is_the_contracts(self):
job = _jobs()[DEFRAG]
assert job["digest"] == job_digest(job)
def test_a_disabled_task_is_not_enabled_and_cannot_be_run(self):
job = _jobs()[REBOOT]
assert job["enabled"] is False
assert job["actions"] == ["enable", "disable"]
def test_a_task_that_never_ran_has_no_last_run_or_result(self):
"""Task Scheduler says 30 November 1999 for never, and 0x41303 for its result."""
job = _jobs()[REBOOT]
assert (job["last_run"], job["last_result"], job["next_run"]) == (None, None, None)
def test_a_task_without_a_description_has_none(self):
assert "description" not in _jobs()[REBOOT]
def test_a_once_trigger_keeps_its_offset(self):
assert _jobs()[REBOOT]["schedule"] == "once at 2026-11-04 03:00+01:00"
def test_an_admins_task_with_two_actions_and_two_triggers(self):
job = _jobs()[BACKUP]
assert job["managed_by"] == "admin"
assert job["run_as"] == "Administrator"
assert (
job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR\nC:\\scripts\\notify.cmd"
)
assert job["schedule"] == (
"daily at 00:00, every 1 hour for 1 day; every 2 days at 12:30 (disabled)"
)
assert job["actions"] == ["enable", "disable", "run"]
def test_json_dates_are_iso_utc(self):
job = _jobs()[BACKUP]
assert job["last_run"] == "2026-11-05T05:00:00+00:00"
assert job["next_run"] == "2026-11-05T06:00:00+00:00"
def test_a_failure_code_is_hex(self):
assert _jobs()[BACKUP]["last_result"] == "0x80070002"
def test_an_applications_task(self):
job = _jobs()[DUMP]
assert job["managed_by"] == "application"
assert job["name"] == "nightly-dump"
assert job["description"] == "Dump the database"
assert (job["schedule"], job["schedule_kind"]) == ("30 2 * * *", "cron")
assert job["command"] == "pg_dump -f D:\\dump.sql app"
assert job["run_as"] == "backup"
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
assert job["last_result"] == "0x1"
assert job["last_run"] == "2026-11-03T01:30:04.123456+00:00"
def test_an_applications_digest_covers_its_triggers(self):
"""Triggers changed by hand change the digest, although the cron line stays."""
changed = _reading()
changed["tasks"][3]["triggers"][0]["start"] = "2020-01-01T03:30:00"
assert _digest(DUMP, changed) != _digest(DUMP)
assert _jobs(changed)[DUMP]["schedule"] == "30 2 * * *"
def test_an_application_task_without_its_schedule_line_shows_its_triggers(self):
reading = _reading()
reading["tasks"][3]["description"] = "napalm-scheduled-job: nightly-dump"
job = _jobs(reading)[DUMP]
assert (job["managed_by"], job["name"]) == ("application", "nightly-dump")
assert "description" not in job
assert (job["schedule"], job["schedule_kind"]) == ("trigger at 02:30", "triggers")
def test_an_application_task_whose_action_was_changed_shows_it(self):
reading = _reading()
reading["tasks"][3]["actions"][0]["arguments"] = "/c whoami"
assert _jobs(reading)[DUMP]["command"] == "%SystemRoot%\\System32\\cmd.exe /c whoami"
@pytest.mark.parametrize(
("path", "name"),
[("\\Vendor\\", "nightly-dump"), ("\\", "other-name"), ("\\", "Nightly Dump")],
)
def test_the_marker_counts_only_on_the_root_task_of_that_name(self, path, name):
reading = _reading()
reading["tasks"][3].update(path=path, name=name)
job = _jobs(reading)[f"task:{path}{name}"]
assert job["managed_by"] == "admin"
assert "edit" not in job["actions"]
assert "name" not in job
def test_a_group_principal_a_com_handler_and_event_triggers(self):
job = _jobs()[UPDATER]
assert job["run_as"] == "Users"
assert job["command"] == "COM handler {A6BA00FE-40E8-477C-B713-C64A14F18ADB}"
assert job["schedule"] == "at logon after 15 minutes; at startup; session state change"
assert job["enabled"] is True
assert job["last_result"] == "running"
def test_a_task_that_cannot_be_started_on_demand_does_not_offer_run(self):
assert _jobs()[UPDATER]["actions"] == ["enable", "disable"]
def test_the_time_zone_is_iana(self):
assert _driver().get_scheduled_jobs()["time_zone"] == "Europe/Berlin"
def test_an_unknown_time_zone_is_none(self):
reading = _reading()
reading["time_zone"] = "Mars Standard Time"
assert _driver(reading).get_scheduled_jobs()["time_zone"] is None
def test_one_task_arrives_as_a_bare_object(self):
"""ConvertTo-Json unwraps a one-element array, nested ones too."""
task = _reading()["tasks"][2]
task["actions"] = task["actions"][0]
task["triggers"] = task["triggers"][0]
reading = {"time_zone": "UTC", "count": 1, "tasks": task}
(job,) = _driver(reading).get_scheduled_jobs()["jobs"]
assert job["key"] == BACKUP
assert job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR"
assert job["schedule"] == "daily at 00:00, every 1 hour for 1 day"
def test_a_host_without_tasks(self):
reading = {"time_zone": None, "count": 0, "tasks": None}
assert _driver(reading).get_scheduled_jobs() == {"jobs": [], "time_zone": None}
def test_a_reading_cut_short_raises(self):
with pytest.raises(ValueError):
_driver(json.dumps(_reading())[:-40]).get_scheduled_jobs()
def test_a_reading_with_fewer_tasks_than_counted_raises(self):
reading = _reading()
reading["count"] = 6
with pytest.raises(ValueError, match="6"):
_driver(reading).get_scheduled_jobs()
def test_an_empty_answer_raises(self):
with pytest.raises(ValueError):
_driver("").get_scheduled_jobs()
def test_a_failed_reading_raises(self):
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(_reading()) # type: ignore[assignment]
d._transport.reading = None
d._transport.run = lambda script: (_ for _ in ()).throw(PowerShellError("Access denied")) # type: ignore[method-assign]
with pytest.raises(PowerShellError):
d.get_scheduled_jobs()
class TestOddTasks:
def _job(self, **changes: Any) -> dict[str, Any]:
task = _reading()["tasks"][0]
task.update(changes)
return _jobs({"time_zone": None, "count": 1, "tasks": [task]})[DEFRAG]
def test_an_action_without_a_command_or_handler_names_its_class(self):
job = self._job(actions=[{"class": "MSFT_TaskSendEmailAction"}])
assert job["command"] == "MSFT_TaskSendEmailAction"
def test_a_start_and_delay_it_cannot_read_are_kept_as_they_are(self):
trigger = {"class": "MSFT_TaskDailyTrigger", "start": "soon", "delay": "a while"}
assert self._job(triggers=[trigger])["schedule"] == "daily at soon after a while"
def test_a_task_that_never_ran_since_it_was_read_has_no_result(self):
job = self._job(last_result=267011)
assert job["last_run"] is not None
assert job["last_result"] is None
def test_a_negative_result_is_the_same_code(self):
assert self._job(last_result=-2147024894)["last_result"] == "0x80070002"
def test_a_reading_that_is_not_an_object_raises(self):
with pytest.raises(ValueError, match="reading"):
_driver("[]").get_scheduled_jobs()
class TestTimestamps:
@pytest.mark.parametrize(
("value", "iso"),
[
(None, None),
("", None),
("2026-11-03T01:30:00Z", "2026-11-03T01:30:00+00:00"),
("2026-11-03T02:30:00+01:00", "2026-11-03T01:30:00+00:00"),
("2026-11-03T01:30:00", "2026-11-03T01:30:00+00:00"),
("/Date(1793854800000)/", "2026-11-05T05:00:00+00:00"),
("/Date(1793854800000+0100)/", "2026-11-05T05:00:00+00:00"),
(1793854800, "2026-11-05T05:00:00+00:00"),
("1999-11-30T00:00:00", None),
("/Date(943916400000)/", None),
("not a date", None),
],
)
def test_to_iso_utc(self, value, iso):
assert mod._timestamp(value) == iso
class TestTimeZones:
@pytest.mark.parametrize(
("windows", "iana"),
[
("W. Europe Standard Time", "Europe/Berlin"),
("GMT Standard Time", "Europe/London"),
("Eastern Standard Time", "America/New_York"),
("UTC", "Etc/UTC"),
("Tokyo Standard Time", "Asia/Tokyo"),
("Mars Standard Time", None),
(None, None),
],
)
def test_a_windows_zone_id_as_iana(self, windows, iana):
assert iana_time_zone(windows) == iana
def test_every_name_in_the_table_is_a_real_zone(self):
from zoneinfo import ZoneInfo
from napalm_windows.time_zones import WINDOWS_TO_IANA
for name in WINDOWS_TO_IANA.values():
ZoneInfo(name)
# ---------------------------------------------------------------------------
# Enable, disable, run
# ---------------------------------------------------------------------------
class TestManage:
@pytest.mark.parametrize(
("action", "cmdlet"),
[("enable", "Enable-ScheduledTask"), ("disable", "Disable-ScheduledTask")],
)
def test_switches_the_tasks_own_flag(self, action, cmdlet):
d = _driver()
result = d.manage_scheduled_job(DEFRAG, action, digest=_digest(DEFRAG))
(script,) = d._transport.writes
assert cmdlet in script
assert "'\\Microsoft\\Windows\\Defrag\\'" in script
assert "'ScheduledDefrag'" in script
assert result == {"success": True, "output": f"{DEFRAG} {action}d"}
def test_run_says_the_task_was_started_not_that_it_finished(self):
d = _driver()
result = d.manage_scheduled_job(DEFRAG, "run", digest=_digest(DEFRAG))
(script,) = d._transport.writes
assert "Start-ScheduledTask" in script
assert result["success"] is True
assert "started" in result["output"]
assert "next reading" in result["output"]
def test_reads_again_before_it_writes(self):
d = _driver()
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
assert d._transport.sent[0] == mod._PS_SCHEDULED_TASKS
def test_the_task_is_found_by_exact_path_and_name(self):
"""Not by -TaskName, which takes wildcards."""
d = _driver()
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
script = d._transport.writes[0]
assert "-eq '\\Microsoft\\Windows\\Defrag\\'" in script
assert "-eq 'ScheduledDefrag'" in script
assert "-TaskName" not in script
def test_a_quote_in_a_task_name_is_doubled(self):
d = _driver()
d.manage_scheduled_job(BACKUP, "disable", digest=_digest(BACKUP))
assert "'Admin''s backup'" in d._transport.writes[0]
def test_a_changed_task_is_not_switched(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.manage_scheduled_job(DEFRAG, "disable", digest="0" * 16)
assert d._transport.writes == []
def test_an_unknown_task_raises_lookup_error(self):
with pytest.raises(LookupError):
_driver().manage_scheduled_job("task:\\nope", "run", digest="0" * 16)
def test_an_unknown_action_is_refused_before_anything_is_sent(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="action"):
d.manage_scheduled_job(DEFRAG, "delete", digest=_digest(DEFRAG))
assert d._transport.writes == []
def test_a_disabled_task_is_not_run(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="run"):
d.manage_scheduled_job(REBOOT, "run", digest=_digest(REBOOT))
assert d._transport.writes == []
def test_what_powershell_says_is_the_result(self):
d = _driver(fail="Access is denied.")
result = d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
assert result == {"success": False, "output": "Access is denied."}
# ---------------------------------------------------------------------------
# An application's own task
# ---------------------------------------------------------------------------
class TestPut:
def test_creates_the_task_in_the_root_folder_from_xml(self):
d = _driver(_without_dump())
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
(script,) = d._transport.writes
assert "Register-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Xml '" in script
assert "-Force" in script
assert result == {"success": True, "output": f"{DUMP} created"}
def test_the_xml_carries_the_definition(self):
d = _driver(_without_dump())
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
script = d._transport.writes[0]
assert task_xml.task_xml(_spec()).replace("'", "''") in script # type: ignore[arg-type]
def test_a_task_of_that_name_there_already(self):
d = _driver()
with pytest.raises(ScheduledJobChanged, match="already"):
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
assert d._transport.writes == []
def test_an_admins_root_task_of_that_name_is_not_overwritten(self):
reading = _reading()
reading["tasks"][3]["description"] = "mine"
d = _driver(reading)
with pytest.raises(ScheduledJobChanged, match="already"):
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
with pytest.raises(ScheduledJobRefused, match="application"):
d.put_scheduled_job(_spec(), digest=_digest(DUMP, reading)) # type: ignore[arg-type]
assert d._transport.writes == []
def test_changes_its_own_task_with_the_digest_it_saw(self):
d = _driver()
result = d.put_scheduled_job(_spec(schedule="*/5 * * * *"), digest=_digest(DUMP)) # type: ignore[arg-type]
assert "Register-ScheduledTask" in d._transport.writes[0]
assert "<Interval>PT5M</Interval>" in d._transport.writes[0]
assert result == {"success": True, "output": f"{DUMP} changed"}
def test_a_changed_task_is_not_overwritten(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
assert d._transport.writes == []
def test_a_task_that_went_away_is_not_changed(self):
d = _driver(_without_dump())
with pytest.raises(LookupError):
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
def test_a_spec_the_contract_refuses_is_refused_before_anything_is_sent(self):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="name"):
d.put_scheduled_job(_spec(name="Nightly Dump")) # type: ignore[arg-type]
assert d._transport.sent == []
def test_a_schedule_task_scheduler_cannot_take_is_refused_before_anything_is_sent(self):
d = _driver(_without_dump())
with pytest.raises(ScheduledJobRefused, match="weekday"):
d.put_scheduled_job(_spec(schedule="0 0 1 * 1")) # type: ignore[arg-type]
assert d._transport.sent == []
def test_quotes_in_the_command_are_doubled_for_powershell(self):
d = _driver(_without_dump())
d.put_scheduled_job(_spec(command="echo it's done’")) # type: ignore[arg-type]
script = d._transport.writes[0]
assert "echo it''s done’’" in script
body = script.split("-Xml '", 1)[1].rsplit("' -Force", 1)[0]
for quote in ("'", "‘", "’", "‚", "‛"):
assert quote not in body.replace(quote * 2, "")
def test_what_powershell_says_is_the_result(self):
d = _driver(_without_dump(), fail="The user name or password is incorrect.")
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
assert result == {"success": False, "output": "The user name or password is incorrect."}
class TestDelete:
def test_unregisters_its_own_task(self):
d = _driver()
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
(script,) = d._transport.writes
assert (
"Unregister-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Confirm:$false"
in script
)
assert result == {"success": True, "output": f"{DUMP} deleted"}
@pytest.mark.parametrize("key", [DEFRAG, BACKUP])
def test_a_task_an_application_did_not_write_is_refused(self, key):
d = _driver()
with pytest.raises(ScheduledJobRefused, match="application"):
d.delete_scheduled_job(key, digest=_digest(key))
assert d._transport.writes == []
def test_a_changed_task_is_not_deleted(self):
d = _driver()
with pytest.raises(ScheduledJobChanged):
d.delete_scheduled_job(DUMP, digest="0" * 16)
assert d._transport.writes == []
def test_an_unknown_task_raises_lookup_error(self):
with pytest.raises(LookupError):
_driver().delete_scheduled_job("task:\\nope", digest="0" * 16)
def test_what_powershell_says_is_the_result(self):
d = _driver(fail="Access is denied.")
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
assert result == {"success": False, "output": "Access is denied."}
def test_a_written_task_reads_back_as_the_spec():
"""What put writes, the reading parses back to the same cron line and command."""
spec = _spec(command='"C:\\Program Files\\app\\run.exe" --quiet & echo done')
xml = task_xml.task_xml(spec) # type: ignore[arg-type]
execute, arguments = task_xml.command_action(spec["command"])
reading = _reading()
task = copy.deepcopy(reading["tasks"][3])
task["actions"] = [{"class": "MSFT_TaskExecAction", "execute": execute, "arguments": arguments}]
task["description"] = task_xml.description(spec) # type: ignore[arg-type]
reading["tasks"][3] = task
job = _jobs(reading)[DUMP]
assert (job["command"], job["schedule"], job["description"]) == (
spec["command"],
spec["schedule"],
spec["description"],
)
assert f"<Command>{execute}</Command>" in xml
def test_an_update_run_task_is_the_drivers_own_and_offers_nothing() -> None:
"""A run's SYSTEM task (``windows_update_run``) is no administrator's job, and while it
exists it is not to be switched or started again (netork#2892)."""
reading = _reading()
task = copy.deepcopy(reading["tasks"][0])
task.update(path="\\napalm-windows\\", name="update-run-0123456789ab", description="")
reading["tasks"].append(task)
reading["count"] += 1
job = _jobs(reading)["task:\\napalm-windows\\update-run-0123456789ab"]
assert job["managed_by"] == "application"
assert job["actions"] == []
+125
View File
@@ -0,0 +1,125 @@
"""The host's services and how each one's last run ended (NetOrk/netork#2897).
``Win32_Service`` says whether a service runs and how it starts, and also what its
last run ended with: ``ExitCode`` (``1066`` hands over to
``ServiceSpecificExitCode``, ``1077`` is "not started since boot"). Together with
whether a trigger starts it (a ``TriggerInfo`` key under the service) that tells a
service that died from one stopped on purpose. The reading is the shape of
tests/fixtures/synthetic/services.json.
"""
from __future__ import annotations
import json
from pathlib import Path
from napalm_windows import WindowsDriver
from napalm_windows import services as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "services.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 if script == mod._PS_SERVICES else ""
def _services(answer: str | None = None) -> dict[str, dict]:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer)
return {s["name"]: s for s in d.get_services()}
class TestRunningAndEnabled:
def test_maps_state_and_start_mode(self):
services = _services()
assert {n: (s["running"], s["enabled"], s["pid"]) for n, s in services.items()} == {
"WinRM": (True, True, 1234),
"Spooler": (False, False, 0),
"MSSQL$SQLEXPRESS": (True, True, 4321),
"RemoteRegistry": (False, False, 0),
"wuauserv": (False, False, 0),
"AppReadiness": (False, True, 0),
"BackupAgent": (False, True, 0),
"VendorSync": (False, True, 0),
"BthServ": (False, True, 0),
}
def test_a_single_service_is_still_a_list(self):
one = json.loads(FIXTURE.read_text())[0]
assert list(_services(json.dumps(one))) == ["WinRM"]
def test_nothing_read_is_no_services(self):
assert _services("") == {}
class TestHowTheLastRunEnded:
def test_a_running_service_succeeded(self):
assert _services()["WinRM"] == {
"name": "WinRM",
"running": True,
"enabled": True,
"pid": 1234,
"result": "success",
"exit_code": None,
"trigger_start": False,
"account": "NT AUTHORITY\\NetworkService",
}
def test_one_stopped_on_purpose_succeeded(self):
assert (_services()["Spooler"]["result"], _services()["Spooler"]["exit_code"]) == (
"success",
None,
)
def test_one_not_started_since_boot_has_no_result(self):
"""1077: a delayed or a demand-start service that has not run yet."""
service = _services()["AppReadiness"]
assert (service["result"], service["exit_code"]) == (None, None)
def test_one_that_died_ended_with_its_exit_code(self):
"""1067: the process terminated unexpectedly."""
service = _services()["BackupAgent"]
assert (service["result"], service["exit_code"]) == ("exit-code", 1067)
def test_a_service_specific_error_is_the_services_own_code(self):
service = _services()["VendorSync"]
assert (service["result"], service["exit_code"]) == ("exit-code", 2147942405)
def test_a_trigger_start_service_says_so(self):
assert _services()["BthServ"]["trigger_start"] is True
assert _services()["BackupAgent"]["trigger_start"] is False
def test_the_account_it_runs_as(self):
assert _services()["BackupAgent"]["account"] == "CORP\\svc-backup"
assert _services()["BthServ"]["account"] is None
def test_a_reading_without_the_new_fields_says_nothing_of_them(self):
"""An older script's answer: running and enabled only, nothing invented."""
old = [{"name": "WinRM", "state": "Stopped", "start_mode": "Auto", "pid": 0}]
service = _services(json.dumps(old))["WinRM"]
assert (service["result"], service["exit_code"], service["trigger_start"]) == (
None,
None,
False,
)
class TestTheScript:
def test_exit_codes_leave_the_host_as_wide_integers(self):
"""``ServiceSpecificExitCode`` is a UInt32: ``[int]`` would throw on an HRESULT."""
assert "[int64]$_.ExitCode" in mod._PS_SERVICES
assert "[int64]$_.ServiceSpecificExitCode" in mod._PS_SERVICES
def test_trigger_start_is_read_once_from_the_registry(self):
assert r"Services\*\TriggerInfo" in mod._PS_SERVICES
assert "-ErrorAction SilentlyContinue" in mod._PS_SERVICES
def test_a_list_goes_through_input_object(self):
assert "-InputObject @(" in mod._PS_SERVICES
+317
View File
@@ -0,0 +1,317 @@
"""Disks, pools, volumes and drive health on Windows, without smartctl (NetOrk/netork#2896).
Each reading is one script whose JSON a fake host answers from
tests/fixtures/synthetic/: ``disks_server.json`` (an NVMe SSD, two SATA disks in a
Storage Spaces pool, a RAID controller's logical disk and a Storage Spaces virtual
disk), ``disks_vm.json`` (a Hyper-V guest's virtual disk with empty reliability
counters), ``storage_pools.json`` and ``volumes.json``.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import HostStorageMixin, OSDriver
from napalm_device_types.roles import primary_role_of, role_keys_of
from napalm_windows import WindowsDriver
from napalm_windows import storage as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
def _load(name: str) -> Any:
return json.loads((FIXTURES / name).read_text())
class FakeHost:
"""Answers each storage script with *answers*' entry for it."""
def __init__(self, answers: dict[str, Any]) -> None:
self.answers = answers
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
answer = self.answers[script]
return answer if isinstance(answer, str) else json.dumps(answer)
def close(self) -> None:
self.is_open = False
def _driver(**answers: Any) -> WindowsDriver:
scripts = {
"disks": mod._PS_DISKS,
"pools": mod._PS_STORAGE_POOLS,
"volumes": mod._PS_VOLUMES,
}
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeHost({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
return d
def _server() -> WindowsDriver:
return _driver(
disks=_load("disks_server.json"),
pools=_load("storage_pools.json"),
volumes=_load("volumes.json"),
)
# ---------------------------------------------------------------------------
# The contract
# ---------------------------------------------------------------------------
class TestContract:
def test_a_host_with_storage_stays_a_host(self):
assert issubclass(WindowsDriver, HostStorageMixin)
assert "storage" not in role_keys_of(WindowsDriver)
assert primary_role_of(WindowsDriver) == primary_role_of(OSDriver)
def test_every_getter_is_there(self):
for name in ("get_disks", "get_disk_pools", "get_volumes", "get_disk_smart"):
assert callable(getattr(WindowsDriver, name)), name
@pytest.mark.parametrize("script", ["_PS_DISKS", "_PS_STORAGE_POOLS", "_PS_VOLUMES"])
def test_scripts_follow_the_driver_conventions(self, script):
text = getattr(mod, script)
assert "$ErrorActionPreference = 'Stop'" in text
assert "ConvertTo-Json" in text
assert "Get-Command" in text # a missing cmdlet is "not supported", not an error
def test_counters_are_read_per_disk_and_may_fail(self):
"""Get-StorageReliabilityCounter needs an administrator and is missing on some
virtual disks: one disk's failure is that disk's missing counter."""
assert "try { $counter = $disk | Get-StorageReliabilityCounter }" in mod._PS_DISKS
assert "catch { $counter = $null }" in mod._PS_DISKS
def test_no_smartctl(self):
for script in (mod._PS_DISKS, mod._PS_STORAGE_POOLS, mod._PS_VOLUMES):
assert "smartctl" not in script
# ---------------------------------------------------------------------------
# get_disks
# ---------------------------------------------------------------------------
class TestDisks:
def test_an_nvme_ssd(self):
disk = _server().get_disks()[0]
assert disk == {
"slot": "PhysicalDisk0",
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"vendor": "",
"type": "nvme",
"size": 1000204886016,
"rpm": 0,
"temperature": 41,
"health": "healthy",
"pool": "",
}
def test_a_pool_member_with_a_warning(self):
disk = _server().get_disks()[1]
assert disk["slot"] == "PhysicalDisk1"
assert disk["serial"] == "WD-WCC7K1ABCDEF" # ATA serials come padded
assert (disk["type"], disk["rpm"], disk["temperature"]) == ("hdd", 5400, 36)
assert (disk["health"], disk["pool"]) == ("warning", "Pool1")
def test_a_zero_temperature_and_an_unknown_speed_are_unknown(self):
disk = _server().get_disks()[2]
assert (disk["temperature"], disk["rpm"]) == (-1, 0)
assert disk["health"] == "healthy" # a real disk with thin counters keeps its verdict
def test_a_raid_logical_disk_has_no_drive_health(self):
"""Windows calls the controller's logical disk Healthy; that is no drive's verdict."""
disk = _server().get_disks()[3]
assert (disk["type"], disk["temperature"], disk["health"]) == ("unknown", -1, "unknown")
def test_a_storage_spaces_virtual_disk_is_no_physical_disk(self):
slots = [d["slot"] for d in _server().get_disks()]
assert slots == ["PhysicalDisk0", "PhysicalDisk1", "PhysicalDisk3", "PhysicalDisk4"]
def test_a_virtual_disk_with_empty_counters(self):
"""Temperature -1 and health "unknown", not zeros and not a "healthy" nobody
measured."""
[disk] = _driver(disks=_load("disks_vm.json")).get_disks()
assert disk["temperature"] == -1
assert disk["health"] == "unknown"
assert disk["type"] == "unknown"
def test_bad_news_is_never_unknown(self):
raw = _load("disks_vm.json")
raw["disks"][0]["health"] = "Unhealthy"
assert _driver(disks=raw).get_disks()[0]["health"] == "failed"
def test_a_disk_without_a_number_is_named_by_its_id(self):
raw = _load("disks_vm.json")
raw["disks"][0]["device_id"] = ""
slot = _driver(disks=raw).get_disks()[0]["slot"]
assert slot == "60022480A1B2C3D4E5F60718293A4B5C"
def test_without_the_storage_module_there_are_none(self):
assert _driver(disks={"supported": False}).get_disks() == []
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="disk reading came back empty"):
_driver(disks="").get_disks()
def test_one_disk_arrives_bare(self):
"""ConvertTo-Json unwraps a one-element array; the parse wraps it again."""
raw = _load("disks_vm.json")
raw["disks"] = raw["disks"][0]
assert len(_driver(disks=raw).get_disks()) == 1
# ---------------------------------------------------------------------------
# get_disk_smart
# ---------------------------------------------------------------------------
class TestDiskSmart:
def test_the_reliability_counters_of_an_nvme_ssd(self):
smart = _server().get_disk_smart()
assert smart["PhysicalDisk0"] == {
"model": "Samsung SSD 980 PRO 1TB",
"serial": "0025_385A_11B2_2C33.",
"type": "nvme",
"size": 1000204886016,
"health": "ok",
"wearout": None,
"temperature": 41,
"percentage_used": 3,
"available_spare": None,
"reallocated_sectors": None,
"power_on_hours": 5120,
"temperature_max": 68,
"read_errors_uncorrected": 0,
"write_errors_uncorrected": 0,
}
def test_a_disk_with_errors_and_a_warning(self):
entry = _server().get_disk_smart()["PhysicalDisk1"]
assert entry["health"] == "warning"
assert entry["read_errors_uncorrected"] == 12
assert entry["percentage_used"] is None # a spinning disk does not wear out by writes
def test_thin_counters_are_none_where_empty(self):
entry = _server().get_disk_smart()["PhysicalDisk3"]
assert entry["temperature"] is None
assert entry["power_on_hours"] == 30990
assert entry["read_errors_uncorrected"] is None
def test_disks_that_report_nothing_are_left_out(self):
assert set(_server().get_disk_smart()) == {
"PhysicalDisk0",
"PhysicalDisk1",
"PhysicalDisk3",
}
def test_a_virtual_host_has_no_drive_health(self):
assert _driver(disks=_load("disks_vm.json")).get_disk_smart() == {}
def test_without_the_counter_cmdlet_there_is_none(self):
raw = _load("disks_server.json")
raw["counters"] = False
for disk in raw["disks"]:
disk["counter"] = None
assert _driver(disks=raw).get_disk_smart() == {}
def test_without_the_storage_module_there_is_none(self):
assert _driver(disks={"supported": False}).get_disk_smart() == {}
# ---------------------------------------------------------------------------
# get_disk_pools
# ---------------------------------------------------------------------------
class TestPools:
def test_a_degraded_mirror(self):
assert _server().get_disk_pools() == {
"Pool1": {
"name": "Pool1",
"type": "storage-spaces",
"level": "mirror",
"status": "degraded",
"total": 8001574060032,
"used": 2199023255552,
"available": 5802550804480,
"disks": ["PhysicalDisk1", "PhysicalDisk3"],
"auto_expand": False,
"dedup": False,
"compression": "off",
}
}
@pytest.mark.parametrize(
("health", "resiliency", "status", "level"),
[
("Healthy", "Simple", "online", "stripe"),
("Unhealthy", "Parity", "faulted", "parity"),
("Unknown", "", "unknown", "unknown"),
],
)
def test_status_and_level(self, health, resiliency, status, level):
raw = _load("storage_pools.json")
raw["pools"][0].update(health=health, resiliency=resiliency)
pool = _driver(pools=raw).get_disk_pools()["Pool1"]
assert (pool["status"], pool["level"]) == (status, level)
def test_no_pools(self):
assert _driver(pools={"supported": True, "pools": []}).get_disk_pools() == {}
def test_without_storage_spaces_there_are_none(self):
assert _driver(pools={"supported": False}).get_disk_pools() == {}
# ---------------------------------------------------------------------------
# get_volumes
# ---------------------------------------------------------------------------
class TestVolumes:
def test_the_system_drive(self):
assert _server().get_volumes()["C:"] == {
"name": "C:",
"pool": "",
"type": "filesystem",
"total": 999483936768,
"used": 287138238464,
"available": 712345698304,
"mountpoint": "C:\\",
"compression": "",
"dedup": False,
"readonly": False,
"snapshots": 0,
"file_system": "NTFS",
"health": "healthy",
}
def test_a_labelled_volume_with_a_warning(self):
volume = _server().get_volumes()["D:"]
assert (volume["name"], volume["file_system"]) == ("Data", "ReFS")
assert volume.get("health") == "warning"
def test_a_volume_mounted_in_a_folder(self):
volume = _server().get_volumes()["C:\\Logs"]
assert (volume["name"], volume["mountpoint"]) == ("Logs", "C:\\Logs\\")
def test_volumes_mounted_nowhere_are_left_out(self):
"""The EFI system partition and the recovery partition hold no one's data."""
assert list(_server().get_volumes()) == ["C:", "D:", "C:\\Logs"]
def test_without_the_storage_module_there_are_none(self):
assert _driver(volumes={"supported": False}).get_volumes() == {}
def test_an_empty_answer_could_not_look(self):
with pytest.raises(ValueError, match="volume reading came back empty"):
_driver(volumes="").get_volumes()
+93
View File
@@ -0,0 +1,93 @@
"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888).
One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``;
a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell
server as the classes describe it. The placeholders are napalm-device-types' own
(``clean_system_identity``).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import system_identity as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _driver(**changes: Any) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes}))
return d
def test_reads_the_identity_and_the_firmware():
assert _driver().get_system_identity() == {
"system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732",
"product_serial": "4B5QM72",
"board_serial": ".4B5QM72.CNCMS0012345AB.",
"bios_vendor": "Dell Inc.",
"bios_version": "2.19.0",
"bios_date": "2023-08-15",
}
def test_one_script_reads_the_three_classes():
d = _driver()
d.get_system_identity()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_SYSTEM_IDENTITY
for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"):
assert cls in script
@pytest.mark.parametrize(
("field", "value"),
[
("product_serial", "To be filled by O.E.M."),
("board_serial", "Default string"),
("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"),
("uuid", "03000200-0400-0500-0006-000700080009"),
("bios_vendor", "To be filled by O.E.M."),
],
)
def test_oem_placeholders_read_as_empty(field, value):
identity = _driver(**{field: value}).get_system_identity()
key = {"uuid": "system_uuid"}.get(field, field)
assert identity[key] == "" # type: ignore[literal-required]
@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"])
def test_a_value_the_host_did_not_give_reads_as_empty(field):
# A VM without a base board, a firmware without a release date: null in the JSON.
identity = _driver(**{field: None}).get_system_identity()
key = {"uuid": "system_uuid"}.get(field, field)
assert identity[key] == "" # type: ignore[literal-required]
def test_the_release_date_is_the_utc_day():
# CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time.
assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15"
def test_an_empty_answer_is_no_reading():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport("")
with pytest.raises(ValueError):
d.get_system_identity()
+260
View File
@@ -0,0 +1,260 @@
"""An application's task as Task Scheduler XML, and a cron expression as its triggers (#8).
A cron shape Task Scheduler can express exactly becomes triggers; every other
shape is refused, naming why.
"""
from __future__ import annotations
import xml.etree.ElementTree as ET # noqa: S405 - parses only what the tests built
from typing import Any
import pytest
from napalm_device_types import ScheduledJobRefused
from napalm_windows import task_xml
NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
def _spec(**changes: Any) -> Any:
spec = {
"name": "nightly-dump",
"schedule": "30 2 * * *",
"run_as": "backup",
"command": "pg_dump -f D:\\dump.sql app",
"enabled": True,
"description": "Dump the database",
}
spec.update(changes)
return spec
def _task(**changes: Any) -> ET.Element:
return ET.fromstring(task_xml.task_xml(_spec(**changes))) # noqa: S314
def _text(task: ET.Element, path: str) -> str | None:
found = task.find(path, NS)
return None if found is None else found.text
def _triggers(schedule: str) -> list[dict[str, Any]]:
"""Each trigger as start, repetition and day schedule, for comparing."""
triggers = []
found = _task(schedule=schedule).find("t:Triggers", NS)
assert found is not None
for trigger in found:
tag = trigger.tag.split("}")[1]
entry: dict[str, Any] = {"type": tag}
if tag == "CalendarTrigger":
entry["start"] = _text(trigger, "t:StartBoundary")
entry["repeat"] = (
_text(trigger, "t:Repetition/t:Interval"),
_text(trigger, "t:Repetition/t:Duration"),
)
schedule_by = next(c for c in trigger if c.tag.split("}")[1].startswith("Schedule"))
entry["by"] = schedule_by.tag.split("}")[1]
entry["days"] = [d.text for d in schedule_by.iter(f"{{{NS['t']}}}Day")]
entry["names"] = [
c.tag.split("}")[1]
for part in ("DaysOfWeek", "Months")
for parent in schedule_by.iter(f"{{{NS['t']}}}{part}")
for c in parent
]
triggers.append(entry)
return triggers
class TestTriggers:
def test_daily_at_one_time(self):
assert _triggers("30 2 * * *") == [
{
"type": "CalendarTrigger",
"start": "2020-01-01T02:30:00",
"repeat": (None, None),
"by": "ScheduleByDay",
"days": [],
"names": [],
}
]
def test_the_daily_alias(self):
assert [t["start"] for t in _triggers("@daily")] == ["2020-01-01T00:00:00"]
def test_weekdays_at_two_times_are_two_weekly_triggers(self):
triggers = _triggers("0 8,17 * * 1-5")
assert [t["start"] for t in triggers] == ["2020-01-01T08:00:00", "2020-01-01T17:00:00"]
assert {t["by"] for t in triggers} == {"ScheduleByWeek"}
assert triggers[0]["names"] == ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
def test_sunday_is_0_and_7(self):
assert _triggers("0 0 * * 0")[0]["names"] == _triggers("0 0 * * 7")[0]["names"]
assert _triggers("0 0 * * 7")[0]["names"] == ["Sunday"]
def test_every_five_minutes_is_one_repetition(self):
assert _triggers("*/5 * * * *") == [
{
"type": "CalendarTrigger",
"start": "2020-01-01T00:00:00",
"repeat": ("PT5M", "PT23H56M"),
"by": "ScheduleByDay",
"days": [],
"names": [],
}
]
def test_every_quarter_hour_in_working_hours(self):
(trigger,) = _triggers("*/15 8-17 * * 1-5")
assert (trigger["start"], trigger["repeat"]) == (
"2020-01-01T08:00:00",
("PT15M", "PT9H46M"),
)
assert trigger["by"] == "ScheduleByWeek"
def test_every_six_hours(self):
(trigger,) = _triggers("0 */6 * * *")
assert trigger["repeat"] == ("PT6H", "PT18H1M")
def test_every_minute(self):
(trigger,) = _triggers("* * * * *")
assert (trigger["start"], trigger["repeat"]) == ("2020-01-01T00:00:00", ("PT1M", "PT24H"))
def test_a_step_that_does_not_divide_the_hour_repeats_within_each_hour(self):
"""*/7 fires at :56 and then at :00 -- four minutes, not seven: one repetition per hour."""
triggers = _triggers("*/7 * * * *")
assert len(triggers) == 24
assert triggers[1]["start"] == "2020-01-01T01:00:00"
assert {t["repeat"] for t in triggers} == {("PT7M", "PT57M")}
def test_two_hours_of_every_other_minute(self):
triggers = _triggers("*/2 8,17 * * *")
assert [(t["start"], t["repeat"]) for t in triggers] == [
("2020-01-01T08:00:00", ("PT2M", "PT59M")),
("2020-01-01T17:00:00", ("PT2M", "PT59M")),
]
def test_days_of_the_month(self):
(trigger,) = _triggers("0 3 1,15 * *")
assert (trigger["by"], trigger["days"]) == ("ScheduleByMonth", ["1", "15"])
assert len(trigger["names"]) == 12
def test_some_months_only(self):
(trigger,) = _triggers("0 0 * 1,jul *")
assert trigger["by"] == "ScheduleByMonth"
assert trigger["days"] == [str(d) for d in range(1, 32)]
assert trigger["names"] == ["January", "July"]
def test_reboot_is_a_boot_trigger(self):
assert _triggers("@reboot") == [{"type": "BootTrigger"}]
@pytest.mark.parametrize(
("schedule", "why"),
[
("0 0 1 * 1", "either"),
("0 0 */2 * 1", "weekday"),
("0 0 * 1 1", "weekday"),
("0,1,5 * * * *", "48"),
],
)
def test_a_shape_task_scheduler_cannot_take_is_refused(self, schedule, why):
with pytest.raises(ScheduledJobRefused, match=why):
task_xml.task_xml(_spec(schedule=schedule))
def test_an_expression_cron_would_not_take_is_refused(self):
with pytest.raises(ScheduledJobRefused, match="range"):
task_xml.triggers("61 * * * *")
def test_at_most_48_triggers(self):
assert len(_triggers("0,30 0-23 * * *")) == 1 # one repetition
assert len(_triggers("0,20 0-11,13-23 * * *")) == 46
with pytest.raises(ScheduledJobRefused, match="48"):
task_xml.task_xml(_spec(schedule="0,20,30 0-11,13-23 * * *"))
class TestTask:
def test_the_description_names_the_job_and_keeps_its_cron_line(self):
assert _text(_task(), "t:RegistrationInfo/t:Description") == (
"napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *"
)
def test_a_job_without_a_description(self):
assert task_xml.description(_spec(description="")) == (
"napalm-scheduled-job: nightly-dump\nschedule: 30 2 * * *"
)
def test_the_command_runs_in_cmd(self):
task = _task(command='"C:\\Program Files\\app.exe" -x & echo <done>')
assert _text(task, "t:Actions/t:Exec/t:Command") == "%SystemRoot%\\System32\\cmd.exe"
assert _text(task, "t:Actions/t:Exec/t:Arguments") == (
'/d /s /c ""C:\\Program Files\\app.exe" -x & echo <done>"'
)
def test_the_xml_is_escaped(self):
raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z"))
assert "a &amp; b &lt; c" in raw
assert "x &gt; y &amp; z" in raw
def test_a_user_runs_without_a_stored_password(self):
task = _task(run_as="backup")
assert _text(task, "t:Principals/t:Principal/t:UserId") == "backup"
assert _text(task, "t:Principals/t:Principal/t:LogonType") == "S4U"
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "LeastPrivilege"
@pytest.mark.parametrize("run_as", ["SYSTEM", "system"])
def test_system_is_the_local_system_account(self, run_as):
task = _task(run_as=run_as)
assert _text(task, "t:Principals/t:Principal/t:UserId") == "S-1-5-18"
assert _text(task, "t:Principals/t:Principal/t:LogonType") is None
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "HighestAvailable"
@pytest.mark.parametrize("enabled", [True, False])
def test_enabled_is_the_tasks_flag(self, enabled):
assert _text(_task(enabled=enabled), "t:Settings/t:Enabled") == str(enabled).lower()
def test_runs_like_cron_on_battery_and_without_catching_up(self):
task = _task()
assert _text(task, "t:Settings/t:DisallowStartIfOnBatteries") == "false"
assert _text(task, "t:Settings/t:StopIfGoingOnBatteries") == "false"
assert _text(task, "t:Settings/t:StartWhenAvailable") == "false"
assert _text(task, "t:Settings/t:MultipleInstancesPolicy") == "IgnoreNew"
def test_a_command_is_one_line(self):
with pytest.raises(ScheduledJobRefused, match="one line"):
task_xml.task_xml(_spec(command="echo a\necho b"))
def test_a_control_character_is_refused(self):
with pytest.raises(ScheduledJobRefused, match="control"):
task_xml.task_xml(_spec(command="echo \x07"))
def test_trailing_whitespace_of_the_command_is_dropped(self):
assert task_xml.command_action("echo hi\n") == (
"%SystemRoot%\\System32\\cmd.exe",
'/d /s /c "echo hi"',
)
@pytest.mark.parametrize(
("execute", "arguments", "command"),
[
("%SystemRoot%\\System32\\cmd.exe", '/d /s /c "echo hi"', "echo hi"),
("%systemroot%\\system32\\CMD.EXE", '/d /s /c "echo hi"', "echo hi"),
("%SystemRoot%\\System32\\cmd.exe", "/c echo hi", None),
("powershell.exe", '/d /s /c "echo hi"', None),
("%SystemRoot%\\System32\\cmd.exe", None, None),
],
)
def test_the_command_back_from_the_action(self, execute, arguments, command):
assert task_xml.own_command(execute, arguments) == command
+289
View File
@@ -0,0 +1,289 @@
"""Time sync on Windows: w32time and the time zone over PowerShell Remoting (NetOrk/netork#2367).
The reading is one script whose JSON a fake host answers, starting from
tests/fixtures/synthetic/time_sync.json (a workgroup host as Windows installs it:
``time.windows.com,0x9``, Type NTP). The fake host applies what the write scripts
say, so ``verify`` reads back what a host would. The status text is
``w32tm /query /status`` as Windows prints it, in English and in German.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import TimeSyncMixin
from napalm_windows import WindowsDriver
from napalm_windows import time_sync as mod
from napalm_windows.time_zones import IANA_TO_WINDOWS, WINDOWS_TO_IANA, windows_time_zone
from napalm_windows.transport import PowerShellError
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "time_sync.json"
UNSYNCED = (
"Leap Indicator: 3(not synchronized)\nStratum: 0 (unspecified)\n"
"Precision: -23 (119.209ns per tick)\nSource: Local CMOS Clock\n"
)
GERMAN = "Sprungindikator: 0(keine Warnung)\nStratum: 3 (Sekundärreferenz - synchr. über (S)NTP)\n"
NOT_STARTED = "Folgender Fehler ist aufgetreten: Der Dienst wurde nicht gestartet. (0x80070426)\n"
class FakeHost:
"""Answers the reading from *state*; applies the write scripts to it."""
def __init__(self, **changes: Any) -> None:
self.state: dict[str, Any] = {**json.loads(FIXTURE.read_text()), **changes}
self.sent: list[str] = []
self.fail: str | None = None
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
if script == mod._PS_TIME_SYNC:
return json.dumps(self.state)
if self.fail:
raise PowerShellError(self.fail)
peers = re.search(r"-Name NtpServer -Value '([^']*)'", script)
if peers and "-Name Type -Value 'NTP'" in script and "w32tm /config /update" in script:
self.state.update(type="NTP", ntp_server=peers.group(1), service="Running")
zone = re.search(r"Set-TimeZone -Id '([^']*)'", script)
if zone:
self.state.update(zone=zone.group(1), dst_off="0")
marker = re.search(r"-Name IanaTimeZone -Value '([^']*)'", script)
if marker:
self.state["iana_zone"] = marker.group(1)
return ""
def close(self) -> None:
self.is_open = False
@property
def writes(self) -> list[str]:
return [s for s in self.sent if s != mod._PS_TIME_SYNC]
def _driver(**changes: Any) -> tuple[WindowsDriver, FakeHost]:
host = FakeHost(**changes)
d = WindowsDriver("win01", "admin", "secret")
d._transport = host # type: ignore[assignment]
return d, host
# ---------------------------------------------------------------------------
# The zone table (CLDR windowsZones.xml, generated)
# ---------------------------------------------------------------------------
class TestZoneTable:
def test_every_windows_zone_reads_back_as_itself(self):
"""The name a zone is read as is a name that writes that zone."""
for windows, iana in WINDOWS_TO_IANA.items():
assert IANA_TO_WINDOWS[iana] == windows
def test_every_name_is_a_real_zone(self):
from zoneinfo import ZoneInfo
for name in [*WINDOWS_TO_IANA.values(), *IANA_TO_WINDOWS]:
ZoneInfo(name)
@pytest.mark.parametrize(
("iana", "windows"),
[
("Europe/Berlin", "W. Europe Standard Time"),
("Europe/Vienna", "W. Europe Standard Time"),
("Europe/London", "GMT Standard Time"),
("Asia/Kolkata", "India Standard Time"), # CLDR keeps Asia/Calcutta
("Asia/Calcutta", "India Standard Time"),
("Europe/Kyiv", "FLE Standard Time"),
("America/New_York", "Eastern Standard Time"),
("Etc/UTC", "UTC"),
("UTC", "UTC"), # a tzdata link to Etc/UTC
("CET", None), # not a zone CLDR maps
],
)
def test_an_iana_name_as_windows_zone(self, iana, windows):
assert windows_time_zone(iana) == windows
def test_renamed_zones_read_as_their_current_name(self):
assert WINDOWS_TO_IANA["India Standard Time"] == "Asia/Kolkata"
assert WINDOWS_TO_IANA["FLE Standard Time"] == "Europe/Kyiv"
assert WINDOWS_TO_IANA["Greenland Standard Time"] == "America/Nuuk"
# A merge in tzdata is no rename: Reykjavik keeps its name.
assert WINDOWS_TO_IANA["Greenwich Standard Time"] == "Atlantic/Reykjavik"
# ---------------------------------------------------------------------------
# Reading
# ---------------------------------------------------------------------------
class TestRead:
def test_is_offered_and_writes_both(self):
assert issubclass(WindowsDriver, TimeSyncMixin)
assert callable(WindowsDriver.get_time_sync)
assert WindowsDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
def test_a_workgroup_host_as_installed(self):
d, host = _driver()
assert d.get_time_sync() == {
"ntp_servers": ["time.windows.com"],
"timezone": "Europe/Berlin",
"synchronized": True,
"daemon": "w32time",
}
assert host.sent == [mod._PS_TIME_SYNC]
def test_servers_without_their_flags_in_order(self):
d, _ = _driver(ntp_server="ntp1.example.org,0x8 10.0.0.1,0x8 ntp1.example.org,0x1")
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
def test_a_domain_member_reports_the_servers_configured(self):
d, _ = _driver(type="NT5DS")
assert d.get_time_sync()["ntp_servers"] == ["time.windows.com"]
assert d.get_time_sync()["daemon"] == "w32time"
def test_group_policy_overrides_the_local_settings(self):
d, _ = _driver(policy_type="NTP", policy_server="ntp.corp.example,0x8")
assert d.get_time_sync()["ntp_servers"] == ["ntp.corp.example"]
def test_nosync_has_no_source(self):
d, _ = _driver(type="NoSync")
assert d.get_time_sync()["ntp_servers"] == []
@pytest.mark.parametrize(
("service", "status", "synchronized"),
[
("Running", UNSYNCED, False),
("Running", GERMAN, True),
("Running", NOT_STARTED, None),
("Running", None, None),
("Stopped", None, False),
(None, None, None),
],
)
def test_synchronized_from_the_leap_indicator(self, service, status, synchronized):
d, _ = _driver(service=service, status=status)
assert d.get_time_sync()["synchronized"] is synchronized
@pytest.mark.parametrize(
("zone", "marker", "iana"),
[
("W. Europe Standard Time", "Europe/Vienna", "Europe/Vienna"),
("GMT Standard Time", "Europe/Vienna", "Europe/London"), # changed by hand since
("W. Europe Standard Time\u0000\u0000", None, "Europe/Berlin"),
("Some Custom Standard Time", None, None),
("", None, None),
],
)
def test_the_zone(self, zone, marker, iana):
d, _ = _driver(zone=zone, iana_zone=marker)
assert d.get_time_sync()["timezone"] == iana
def test_summer_time_switched_off_is_not_the_zone(self):
d, _ = _driver(dst_off="1", iana_zone="Europe/Berlin")
assert d.get_time_sync()["timezone"] is None
def test_a_cut_reading_raises(self):
d, host = _driver()
host.run = lambda script: "" # type: ignore[method-assign]
with pytest.raises(ValueError):
d.get_time_sync()
# ---------------------------------------------------------------------------
# Writing
# ---------------------------------------------------------------------------
class TestWriteServers:
def test_sets_manual_peers_in_client_mode(self):
d, host = _driver()
result = d.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"])
assert result["success"], result["output"]
(script,) = host.writes
assert "-Name NtpServer -Value 'ntp1.example.org,0x8 10.0.0.1,0x8'" in script
assert "-Name Type -Value 'NTP'" in script
assert "Start-Service -Name W32Time" in script
assert script.index("Set-ItemProperty") < script.index("w32tm /config /update")
assert d.get_time_sync()["ntp_servers"] == ["ntp1.example.org", "10.0.0.1"]
def test_the_same_servers_again_write_nothing(self):
d, host = _driver(ntp_server="NTP1.example.org,0x8")
result = d.configure_time_sync(ntp_servers=["ntp1.example.org"])
assert result["success"], result["output"]
assert host.writes == []
def test_nosync_with_the_same_servers_is_written(self):
d, host = _driver(type="NoSync", ntp_server="ntp1.example.org,0x8")
assert d.configure_time_sync(ntp_servers=["ntp1.example.org"])["success"]
assert len(host.writes) == 1
@pytest.mark.parametrize("kind", ["NT5DS", "AllSync"])
def test_a_domain_member_is_refused(self, kind):
d, host = _driver(type=kind)
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "domain" in result["steps"][0]["output"]
assert host.writes == []
def test_group_policy_is_refused(self):
d, host = _driver(policy_server="ntp.corp.example,0x8")
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "group policy" in result["steps"][0]["output"]
assert host.writes == []
def test_a_failed_script_fails_the_step(self):
d, host = _driver()
host.fail = "w32tm /config: The service cannot be started (0x80070422)"
result = d.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "0x80070422" in result["steps"][0]["output"]
class TestWriteZone:
def test_sets_the_windows_zone_and_remembers_the_name(self):
d, host = _driver(zone="GMT Standard Time")
result = d.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
(script,) = host.writes
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in script
assert "-Name IanaTimeZone -Value 'Europe/Vienna'" in script
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
def test_the_same_windows_zone_only_remembers_the_name(self):
d, host = _driver()
result = d.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
(script,) = host.writes
assert "Set-TimeZone" not in script
assert d.get_time_sync()["timezone"] == "Europe/Vienna"
def test_the_same_zone_again_writes_nothing(self):
d, host = _driver(iana_zone="Europe/Berlin")
assert d.configure_time_sync(timezone="Europe/Berlin")["success"]
assert host.writes == []
def test_summer_time_off_is_turned_on(self):
d, host = _driver(dst_off="1", iana_zone="Europe/Berlin")
result = d.configure_time_sync(timezone="Europe/Berlin")
assert result["success"], result["output"]
assert "Set-TimeZone -Id 'W. Europe Standard Time'" in host.writes[0]
def test_a_zone_windows_does_not_have_is_refused(self):
d, host = _driver()
result = d.configure_time_sync(timezone="CET")
assert not result["success"]
assert "no Windows time zone" in result["steps"][0]["output"]
assert host.writes == []
def test_servers_and_zone_together(self):
d, host = _driver()
result = d.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="America/New_York")
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
assert d.get_time_sync()["timezone"] == "America/New_York"
+155 -1
View File
@@ -11,7 +11,8 @@ from unittest.mock import patch
import pytest
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.exceptions import AuthenticationError, WinRMTransportError
from pypsrp.complex_objects import PSInvocationState
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from napalm_windows.transport import PowerShellError, PsrpTransport
@@ -120,6 +121,159 @@ class TestRun:
_transport().run("Get-Thing")
class TestRunLast:
"""A script that may take WinRM down with it: a restart, a shutdown."""
def test_a_finished_script_is_true(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = False
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is True
psrp["ps"].return_value.add_script.assert_called_once_with("Restart-Computer")
assert t.is_open is True
def test_the_error_stream_still_raises_powershell_error(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = True
psrp["ps"].return_value.streams.error = ["other users logged on"]
t = _transport()
t.open()
with pytest.raises(PowerShellError, match="other users logged on"):
t.run_last("Restart-Computer")
@pytest.mark.parametrize(
"error",
[
requests.ConnectionError("connection reset by peer"),
requests.ReadTimeout("read timed out"),
WinRMTransportError("http", 503, "Service Unavailable"),
WinRMError("the shell was terminated"),
ConnectionResetError(104, "Connection reset by peer"),
],
)
def test_a_connection_that_breaks_is_false_and_closed(self, psrp, error):
psrp["ps"].return_value.invoke.side_effect = error
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is False
assert t.is_open is False
def test_run_last_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run_last("Restart-Computer")
class _Pipeline:
"""A PowerShell pipeline whose output arrives over several polls, as pypsrp's
``begin_invoke``/``poll_invoke`` deliver a long-running script's."""
def __init__(self, batches, *, errors=(), never_ends=False):
self.batches = [list(b) for b in batches]
self.output: list = []
self.state = PSInvocationState.NOT_STARTED
self.had_errors = bool(errors)
self.streams = type("Streams", (), {"error": list(errors)})()
self.never_ends = never_ends
self.polls: list = []
self.stopped = False
self.script = None
def add_script(self, script):
self.script = script
def begin_invoke(self):
self.state = PSInvocationState.RUNNING
def poll_invoke(self, timeout=None):
self.polls.append(timeout)
if self.batches:
self.output.extend(self.batches.pop(0))
if not self.batches and not self.never_ends:
self.state = PSInvocationState.COMPLETED
def stop(self):
self.stopped = True
self.state = PSInvocationState.STOPPED
class TestRunStreaming:
"""A long-running script: each output line reaches the caller as the host prints it."""
def _open(self, psrp, pipeline, **overrides):
psrp["ps"].return_value = pipeline
t = _transport(**overrides)
t.open()
return t
def test_each_output_object_reaches_the_caller_as_it_arrives(self, psrp):
pipeline = _Pipeline([["one"], [], ["two", None, "three"]])
t = self._open(psrp, pipeline)
seen: list[str] = []
out = t.run_streaming("sfc", seen.append, limit=60)
assert seen == ["one", "two", "three"]
assert out == ["one", "two", "three"]
assert pipeline.script == "sfc"
def test_each_poll_waits_less_than_a_read_of_the_connection(self, psrp):
pipeline = _Pipeline([["a"], ["b"]])
t = self._open(psrp, pipeline, timeout=60)
t.run_streaming("x", lambda _line: None, limit=600)
assert pipeline.polls and all(0 < p < 60 for p in pipeline.polls)
def test_a_short_connection_timeout_still_polls(self, psrp):
pipeline = _Pipeline([["a"]])
t = self._open(psrp, pipeline, timeout=5)
t.run_streaming("x", lambda _line: None, limit=600)
assert pipeline.polls == [2]
def test_the_error_stream_raises_after_the_output_was_passed_on(self, psrp):
pipeline = _Pipeline([["started"]], errors=["Access is denied."])
t = self._open(psrp, pipeline)
seen: list[str] = []
with pytest.raises(PowerShellError, match="Access is denied"):
t.run_streaming("x", seen.append, limit=60)
assert seen == ["started"]
def test_a_script_past_its_limit_is_stopped(self, psrp):
pipeline = _Pipeline([["working"]], never_ends=True)
t = self._open(psrp, pipeline)
clock = iter([0.0, 10.0, 70.0, 130.0])
with (
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
pytest.raises(TimeoutError, match="60 seconds"),
):
t.run_streaming("x", lambda _line: None, limit=60)
assert pipeline.stopped is True
def test_stopping_a_pipeline_that_ended_meanwhile_still_times_out(self, psrp):
pipeline = _Pipeline([["working"]], never_ends=True)
pipeline.stop = lambda: (_ for _ in ()).throw(RuntimeError("not running"))
t = self._open(psrp, pipeline)
clock = iter([0.0, 61.0])
with (
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
pytest.raises(TimeoutError),
):
t.run_streaming("x", lambda _line: None, limit=60)
def test_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run_streaming("x", lambda _line: None, limit=60)
class TestClose:
def test_close_closes_pool_and_connection(self, psrp):
t = _transport()
+76 -16
View File
@@ -28,9 +28,15 @@ def _fixture(name: str) -> str:
class FakeTransport:
"""Answers the driver's scripts from fixtures and records what it was sent."""
def __init__(self, answers: dict[str, str] | None = None, error: str | None = None):
def __init__(
self,
answers: dict[str, str] | None = None,
error: str | None = None,
drops: bool = False,
):
self.answers = answers or {}
self.error = error
self.drops = drops
self.sent: list[str] = []
self.is_open = True
@@ -40,6 +46,14 @@ class FakeTransport:
raise PowerShellError(self.error)
return self.answers.get(script, "")
def run_last(self, script: str) -> bool:
self.sent.append(script)
if self.error:
raise PowerShellError(self.error)
if self.drops:
self.is_open = False
return not self.drops
def close(self) -> None:
self.is_open = False
@@ -297,10 +311,17 @@ class TestGetArpTable:
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
assert arp == [
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": 0.0},
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": 0.0},
{"interface": "Ethernet", "mac": "00:0D:B9:11:22:33", "ip": "10.0.0.1", "age": -1.0},
{"interface": "Ethernet", "mac": "00:15:5D:AA:BB:CC", "ip": "10.0.0.20", "age": -1.0},
]
def test_age_is_unknown(self):
"""Get-NetNeighbor has a state but no age; 0.0 would read as "confirmed
just now" to a caller ranking sightings by freshness (NetOrk/netork#1327)."""
arp = _driver(_PS_ARP=_fixture("arp.json")).get_arp_table()
assert {entry["age"] for entry in arp} == {-1.0}
class TestGetRouteTo:
def test_maps_protocols_and_drops_noise(self):
@@ -349,19 +370,6 @@ class TestGetRouteTo:
assert list(routes) == ["192.168.50.0/24"]
class TestGetServices:
def test_maps_state_and_start_mode(self):
services = _driver(_PS_SERVICES=_fixture("services.json")).get_services()
assert services == [
{"name": "WinRM", "running": True, "enabled": True, "pid": 1234},
{"name": "Spooler", "running": False, "enabled": False, "pid": 0},
{"name": "MSSQL$SQLEXPRESS", "running": True, "enabled": True, "pid": 4321},
{"name": "RemoteRegistry", "running": False, "enabled": False, "pid": 0},
{"name": "wuauserv", "running": False, "enabled": False, "pid": 0},
]
class TestGetListeningSockets:
"""netOrk #673: what listens, and which Windows service it is."""
@@ -483,3 +491,55 @@ class TestManageService:
"success": False,
"output": "Cannot find any service with service name 'nope'.",
}
class TestHostPower:
"""``reboot_host`` and ``shutdown_host``: the clean restart and shutdown of the host
itself, never a forced one (NetOrk/netork#2841)."""
@pytest.mark.parametrize(
("method", "cmdlet"),
[("reboot_host", "Restart-Computer"), ("shutdown_host", "Stop-Computer")],
)
def test_sends_the_cmdlet_without_force(self, method, cmdlet):
d = _driver()
getattr(d, method)()
(script,) = d._transport.sent
assert script.startswith(cmdlet)
assert "-ErrorAction Stop" in script
assert "-Force" not in script
@pytest.mark.parametrize(
("method", "what"), [("reboot_host", "restart"), ("shutdown_host", "shut down")]
)
def test_a_refusal_raises_with_the_hosts_answer(self, method, what):
answer = (
"Failed to restart the computer WIN01 with the following error message: The "
"system shutdown cannot be initiated because there are other users logged on "
"to the computer."
)
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(error=answer)
with pytest.raises(RuntimeError, match=f"refused to {what}: Failed to restart"):
getattr(d, method)()
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_a_connection_dropped_by_the_host_counts_as_accepted(self, method):
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(drops=True)
getattr(d, method)()
assert len(d._transport.sent) == 1
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_before_open_raises_connection_closed(self, method):
with pytest.raises(ConnectionClosedException):
getattr(WindowsDriver("win01", "admin", "secret"), method)()
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_the_capability_is_there_for_introspection(self, method):
assert callable(getattr(WindowsDriver("win01", "admin", "secret"), method, None))
+93
View File
@@ -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
+329
View File
@@ -0,0 +1,329 @@
"""Windows Update: the search, the pending list read from it, and the history (netork#2892).
A fake transport answers each script from tests/fixtures/synthetic/wu_*.json, the JSON
the scripts are written to emit. What a real host emits the fixtures cannot prove --
see the README there.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import PackageIndexMissing
from napalm_windows import WindowsDriver
from napalm_windows import windows_update as mod
from napalm_windows.transport import PowerShellError
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
DEFENDER = "Security-Intelligence-Update-for-Microsoft-Defender-Antivirus-Current-Channel-Broad"
DOTNET = (
"Cumulative-Update-for-.NET-Framework-3.5-4.8-and-4.8.1-for-Microsoft-server-operating-"
"system-version-21H2-for-x64"
)
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
def _fixture(name: str) -> Any:
return json.loads((FIXTURES / f"wu_{name}.json").read_text())
class FakeTransport:
"""Answers each Windows Update script with its canned output; records them all."""
def __init__(self, answers: dict[str, Any]):
self.answers = answers
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
answer = self.answers[script]
if isinstance(answer, Exception):
raise answer
return answer if isinstance(answer, str) else json.dumps(answer)
def close(self) -> None:
self.is_open = False
def _driver(**answers: Any) -> WindowsDriver:
scripts = {
"search": mod._PS_WU_SEARCH,
"pending": mod._PS_WU_PENDING,
"history": mod._PS_WU_HISTORY,
}
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
return d
# ---------------------------------------------------------------------------
# Names
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("title", "name"),
[
(
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
"for x64-based Systems (KB5070000)",
CU,
),
(
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
"(Version 1.441.120.0) - Current Channel (Broad)",
DEFENDER,
),
("Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)", MSRT),
(
"2026-01 Cumulative Update for Windows 11, version 24H2 for x64-based Systems "
"(KB5050009) (26100.2894)",
"Cumulative-Update-for-Windows-11-version-24H2-for-x64-based-Systems",
),
(
"2026-11 Kumulatives Update für Microsoft Server Operating System, Version 21H2 "
"für x64-basierte Systeme (KB5070000)",
"Kumulatives-Update-fur-Microsoft-Server-Operating-System-Version-21H2-fur-"
"x64-basierte-Systeme",
),
],
)
def test_an_update_is_named_by_what_it_keeps_from_month_to_month(title: str, name: str) -> None:
"""Next month's cumulative update replaces this one under the same name, so the time
the host has been waiting for it is not reset each month: the date, the KB article
and the version are left out of the name."""
assert mod.update_name(title, ["5070000"], "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11") == name
assert mod.NAME.fullmatch(name)
def test_a_title_with_nothing_left_is_named_by_its_kb_then_by_its_id() -> None:
assert mod.update_name("(KB5070000)", ["5070000"], "x") == "KB5070000"
assert mod.update_name("", [], "8f5c0d55-3b0f") == "8f5c0d55-3b0f"
def test_a_long_title_is_cut_to_a_name_a_store_keeps() -> None:
name = mod.update_name("Update " * 80, [], "x")
assert len(name) <= mod.NAME_MAX
assert not name.endswith("-")
# ---------------------------------------------------------------------------
# Pending updates: read from the last search, never searching in the poll
# ---------------------------------------------------------------------------
def _pending(**kw: Any) -> dict[str, dict[str, Any]]:
answers = {"pending": _fixture("pending"), **kw}
return {u["name"]: dict(u) for u in _driver(**answers).get_available_updates()}
def test_the_pending_list_is_the_last_search_without_what_was_installed_since() -> None:
"""The Defender update was installed an hour after the search; the cumulative update
has an install in the history, but from before the search -- it is offered again."""
pending = _pending()
assert sorted(pending) == sorted([CU, DOTNET, MSRT])
def test_a_pending_update_says_what_it_fixes() -> None:
cu = _pending()[CU]
assert cu == {
"name": CU,
"current_version": "",
"new_version": "KB5070000",
"origin": "Windows Update",
"security": True,
"title": (
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
"for x64-based Systems (KB5070000)"
),
"advisories": ["KB5070000"],
"cves": ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003"],
"vendor_severity": "Critical",
}
def test_security_is_what_windows_classifies_so() -> None:
pending = _pending()
assert pending[DOTNET]["security"] is True
assert pending[DOTNET]["vendor_severity"] == "Important"
# The removal tool is an update rollup: known, and not a security update.
assert pending[MSRT]["security"] is False
assert pending[MSRT]["vendor_severity"] is None
assert pending[MSRT]["cves"] == []
def test_optional_updates_and_feature_upgrades_are_not_pending() -> None:
"""A preview Windows does not install by itself, and an in-place upgrade of the OS,
are no pending updates: this path installs neither."""
names = set(_pending())
assert not any("Preview" in n for n in names)
assert not any("upgrade" in n for n in names)
def test_definition_updates_count_as_security() -> None:
search = _fixture("search")
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[DEFENDER]["security"] is True
def test_updates_of_the_same_name_are_one_entry() -> None:
search = _fixture("search")
twin = dict(search["updates"][0], id="00000000-0000-4000-8000-000000000001")
twin.update(kb=["5070001"], cves=["CVE-2026-21009"], severity="Moderate")
search["updates"].append(twin)
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
cu = _pending(pending=reading)[CU]
assert cu["new_version"] == "KB5070000 KB5070001"
assert cu["advisories"] == ["KB5070000", "KB5070001"]
assert cu["cves"] == ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003", "CVE-2026-21009"]
assert cu["vendor_severity"] == "Critical" # the higher of the two
def test_an_update_without_a_kb_shows_its_revision() -> None:
search = _fixture("search")
search["updates"][3]["kb"] = []
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[MSRT]["new_version"] == "rev 1"
def test_a_wsus_client_names_its_server() -> None:
search = dict(_fixture("search"), wsus="https://wsus.example.lan:8531")
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[CU]["origin"] == "WSUS https://wsus.example.lan:8531"
def test_no_search_yet_is_a_missing_index_that_a_refresh_cures() -> None:
with pytest.raises(PackageIndexMissing, match="refresh"):
_pending(pending={"search": None, "installed": [], "history_error": None})
def test_a_failed_history_read_keeps_the_search_as_it_was() -> None:
reading = dict(_fixture("pending"), installed=[], history_error="0x8024000C")
assert DEFENDER in _pending(pending=reading)
def test_a_reading_that_is_no_search_raises() -> None:
with pytest.raises(ValueError, match="Windows Update"):
_pending(pending={"search": "[1, 2]", "installed": [], "history_error": None})
def test_the_poll_does_not_search() -> None:
"""The search takes minutes: the poll reads what the refresh found."""
d = _driver(pending=_fixture("pending"))
d.get_available_updates()
assert d._transport.sent == [mod._PS_WU_PENDING] # type: ignore[union-attr]
# ---------------------------------------------------------------------------
# Refresh: the search itself
# ---------------------------------------------------------------------------
def test_the_refresh_searches_and_says_what_it_found() -> None:
result = _driver(search=_fixture("search")).refresh_available_updates()
assert result["success"] is True
assert result["output"] == (
"Windows Update offers 4 updates, 3 of them for security, searched in 94 s."
)
def test_a_refresh_windows_refuses_is_a_failed_refresh() -> None:
d = _driver(search=PowerShellError("Exception from HRESULT: 0x8024402C"))
assert d.refresh_available_updates() == {
"success": False,
"output": "Exception from HRESULT: 0x8024402C",
}
def test_a_search_script_keeps_what_it_found_for_the_poll() -> None:
"""The search writes its reading where only administrators can write, and the poll's
script reads it there."""
assert "Set-ItemProperty" in mod._PS_WU_SEARCH
assert mod.STORE in mod._PS_WU_SEARCH and mod.STORE in mod._PS_WU_PENDING
assert mod.STORE.startswith("HKLM:\\SOFTWARE\\napalm-windows\\")
assert "Type='Software'" in mod._PS_WU_SEARCH # no drivers
# ---------------------------------------------------------------------------
# History
# ---------------------------------------------------------------------------
def _history(since: int | None = None, reading: Any = None) -> list[dict[str, Any]]:
d = _driver(history=_fixture("history") if reading is None else reading)
return [dict(t) for t in d.get_update_history(since)]
def test_each_history_entry_is_a_transaction_newest_first() -> None:
history = _history()
assert [t["start"] for t in history] == sorted((t["start"] for t in history), reverse=True)
first = history[0]
assert first == {
"id": "d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4:200:1:1795603600",
"start": 1795603600,
"end": 1795603600,
"packages": [
{
"name": DEFENDER,
"action": "install",
"old_version": None,
"new_version": "KB2267602",
"title": (
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
"(Version 1.441.120.0) - Current Channel (Broad)"
),
}
],
"requested_by": "Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)",
"command": None,
"error": None,
}
def test_a_failed_install_names_its_error() -> None:
failed = next(t for t in _history() if t["requested_by"] == "napalm-windows")
assert failed["error"] == "failed (0x80240017)"
def test_an_uninstall_removes_its_kb() -> None:
removed = next(t for t in _history() if t["packages"][0]["action"] == "remove")
assert removed["packages"][0]["old_version"] == "KB5007651"
assert removed["packages"][0]["new_version"] is None
def test_an_install_still_running_has_no_end_and_an_unknown_requester() -> None:
running = _history()[-1]
assert running["end"] is None
assert running["requested_by"] is None
assert running["error"] is None
def test_the_history_since_a_moment() -> None:
assert [t["start"] for t in _history(since=1795590000)] == [1795603600, 1795590000]
def test_an_empty_history() -> None:
assert _history(reading="") == []
def test_other_results_are_named() -> None:
entry = dict(_fixture("history")[0], result=5, hresult=0)
assert _history(reading=[entry])[0]["error"] == "aborted"
entry = dict(entry, result=3, hresult=-2145124329)
assert _history(reading=[entry])[0]["error"] == "succeeded with errors (0x80240017)"
def test_one_name_is_unknown_security_when_one_of_its_updates_does_not_say() -> None:
search = _fixture("search")
twin = dict(search["updates"][3], id="00000000-0000-4000-8000-000000000002")
twin["classifications"] = []
search["updates"].append(twin)
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
assert _pending(pending=reading)[MSRT]["security"] is None
+271
View File
@@ -0,0 +1,271 @@
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
The transport is faked: each script the run sends is recognised by what it does and
answered as the host would. The SYSTEM script itself is read here as text; what Windows
Update does with it only a real host can show.
"""
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 windows_update as wu
from napalm_windows import windows_update_run as mod
from napalm_windows.transport import PowerShellError
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
CU_ID = "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11:1"
DOTNET_ID = "1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f:3"
MSRT_ID = "6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c:1"
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
class Host:
"""The host's side of a run: what the sweep finds, and what each look shows."""
def __init__(
self,
looks: list[dict[str, Any]] | None = None,
busy: list[str] | None = None,
start_fails: str | None = None,
):
self.looks = list(looks or [])
self.busy = busy or []
self.start_fails = start_fails
self.sent: list[str] = []
self.is_open = True
def kind(self, script: str) -> str:
if script == wu._PS_WU_PENDING:
return "pending"
if "busy" in script and "Unregister-ScheduledTask" in script:
return "sweep"
if "Register-ScheduledTask" in script:
return "start"
if "$state = 'gone'" in script:
return "follow"
if "Remove-Item -LiteralPath $key" in script:
return "cleanup"
raise AssertionError(f"unexpected script: {script[:80]}")
def run(self, script: str) -> str:
kind = self.kind(script)
self.sent.append(kind)
if kind == "pending":
return (FIXTURES / "wu_pending.json").read_text()
if kind == "sweep":
return json.dumps({"busy": self.busy, "swept": ["update-run-0123456789ab"]})
if kind == "start":
self.start_script = script
if self.start_fails:
raise PowerShellError(self.start_fails)
return ""
if kind == "follow":
return json.dumps(self.looks.pop(0))
return ""
def close(self) -> None:
self.is_open = False
def _look(state: str, log: list[str], result: dict[str, Any] | None = None) -> dict[str, Any]:
return {"state": state, "log": "\n".join(log), "result": json.dumps(result) if result else ""}
def _result(**kw: Any) -> dict[str, Any]:
return {
"reboot_required": False,
"installed": [],
"refused": [],
"failed": [],
"error": None,
**kw,
}
@pytest.fixture(autouse=True)
def no_waiting(monkeypatch: pytest.MonkeyPatch) -> list[float]:
slept: list[float] = []
monkeypatch.setattr(mod.time, "sleep", slept.append)
return slept
def _driver(host: Host) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = host # type: ignore[assignment]
return d
def test_a_run_installs_in_a_system_task_and_hands_on_each_line() -> None:
host = Host(
[
_look("Running", ["Searching Windows Update again for the chosen updates"]),
_look(
"Ready",
[
"Searching Windows Update again for the chosen updates",
"Downloading 1 update(s)",
"Installing 1 update(s); the host is not restarted",
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
"A restart finishes the installation.",
],
_result(installed=[CU_ID], reboot_required=True),
),
]
)
seen: list[str] = []
result = _driver(host).apply_updates([CU], log=seen.append)
assert result["success"] is True
assert "error" not in result
assert host.sent == ["pending", "sweep", "start", "follow", "follow", "cleanup"]
assert seen[0].startswith("Chosen: 2026-11 Cumulative Update")
assert seen[1:] == [
"Searching Windows Update again for the chosen updates",
"Downloading 1 update(s)",
"Installing 1 update(s); the host is not restarted",
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
"A restart finishes the installation.",
]
assert result["output"] == "\n".join(seen)
def test_the_task_gets_exactly_the_updates_chosen_and_runs_as_system() -> None:
host = Host([_look("Ready", [], _result(installed=[CU_ID]))])
_driver(host).apply_updates([CU])
start = host.start_script
assert f"@('{CU_ID}')" in start
assert DOTNET_ID not in start
assert "-UserId 'SYSTEM'" in start and "-RunLevel Highest" in start
assert "Register-ScheduledTask -TaskPath '\\napalm-windows\\'" in start
# The script travels in the run's registry key, never as a file.
assert "-Name Script" in start and ".ps1" not in start
def test_every_pending_update_when_none_is_named() -> None:
host = Host([_look("Ready", [], _result(installed=[CU_ID, DOTNET_ID, MSRT_ID]))])
assert _driver(host).apply_updates([])["success"] is True
for identity in (CU_ID, DOTNET_ID, MSRT_ID):
assert f"'{identity}'" in host.start_script
def test_a_name_the_last_search_does_not_offer_is_refused_and_the_rest_installed() -> None:
host = Host([_look("Ready", ["Installed: x"], _result(installed=[MSRT_ID]))])
seen: list[str] = []
result = _driver(host).apply_updates([MSRT, "Gone-Update"], log=seen.append)
assert seen[0] == "Refused Gone-Update: not offered by the last search"
assert result["success"] is False
assert result["error"] == "1 update(s) refused, 0 failed."
def test_only_names_the_search_does_not_offer_start_nothing() -> None:
host = Host()
result = _driver(host).apply_updates(["Gone-Update"])
assert result["success"] is False
assert host.sent == ["pending"]
def test_nothing_pending_is_nothing_to_install() -> None:
result = mod.install(lambda s: "", {}, [], None)
assert result == {"success": True, "output": "Nothing to install."}
def test_a_name_that_is_no_package_name_is_refused_before_anything_runs() -> None:
host = Host()
with pytest.raises(ValueError, match="Invalid update name"):
_driver(host).apply_updates(["KB1; Restart-Computer"])
assert host.sent == []
def test_what_the_task_refused_or_failed_makes_the_run_fail() -> None:
refused = {"id": CU_ID, "reason": "it asks for input while it installs"}
failed = {"id": DOTNET_ID, "step": "Install", "result": 4, "hresult": -2145124329}
host = Host([_look("Ready", [], _result(refused=[refused], failed=[failed]))])
result = _driver(host).apply_updates([])
assert result["success"] is False
assert result["error"] == "1 update(s) refused, 1 failed."
def test_a_pending_restart_installs_nothing_and_says_so() -> None:
error = "A restart is pending on the host: nothing is installed until it has restarted."
host = Host([_look("Ready", [error], _result(error=error))])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert result["error"] == error
def test_a_task_that_ends_without_a_result_failed_and_is_cleaned_up() -> None:
host = Host([_look("Ready", ["Downloading 1 update(s)"])])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert result["error"] == "The update task ended without a result."
assert host.sent[-1] == "cleanup"
def test_an_earlier_run_still_installing_refuses_this_one() -> None:
host = Host(busy=["update-run-0123456789ab"])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert "still installing" in result["error"]
assert host.sent == ["pending", "sweep"]
def test_a_run_followed_too_long_is_left_to_finish_on_the_host(
monkeypatch: pytest.MonkeyPatch,
) -> None:
clock = iter([0.0, 10.0, mod.FOLLOW_SECONDS + 1.0])
monkeypatch.setattr(mod.time, "monotonic", lambda: next(clock))
host = Host([_look("Running", ["Downloading 1 update(s)"]), _look("Running", [])])
result = _driver(host).apply_updates([CU])
assert result["success"] is False
assert "carries on there" in result["error"]
assert "cleanup" not in host.sent # the next run's sweep deletes it once it ended
def test_a_task_windows_refuses_to_register_raises() -> None:
host = Host(start_fails="Access is denied.")
with pytest.raises(PowerShellError, match="Access is denied"):
_driver(host).apply_updates([CU])
def test_the_follower_waits_between_looks(no_waiting: list[float]) -> None:
host = Host([_look("Running", []), _look("Ready", [], _result(installed=[CU_ID]))])
_driver(host).apply_updates([CU])
assert no_waiting == [mod.POLL_SECONDS, mod.POLL_SECONDS]
# ---------------------------------------------------------------------------
# The SYSTEM script, read as text
# ---------------------------------------------------------------------------
def test_the_system_script_guards_what_it_installs() -> None:
script = mod.run_script("0123456789ab")
assert "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs\\0123456789ab" in script
# A pending restart refuses everything before any download.
assert script.index("$pending -or $installer.RebootRequiredBeforeInstallation") < (
script.index("CreateUpdateDownloader")
)
# Exactly the ID and revision, offered once, quiet, licence accepted on the host.
assert "no longer offered" in script
assert "offered more than once" in script
assert "CanRequestUserInput" in script
assert "EulaAccepted" in script
assert "AcceptEula" not in script
# Never restarts, and Windows Update's history names the run.
assert "Restart-Computer" not in script and "shutdown" not in script.lower()
assert "ClientApplicationID = 'napalm-windows'" in script
def test_the_scripts_quote_what_they_are_given() -> None:
start = mod._script(mod._PS_START, RUN="'x'", TASK="'t'", REQUESTED="'a'", SCRIPT="'s'")
assert "__" not in start
for template in (mod._PS_SWEEP, mod._PS_FOLLOW, mod._PS_CLEANUP):
assert "__" not in mod._script(template, RUN="'x'", TASK="'t'")
+62
View File
@@ -0,0 +1,62 @@
"""tools/windows_zones.py: the generator of napalm_windows/_windows_zones.py."""
from __future__ import annotations
import importlib.util
from pathlib import Path
TOOL = Path(__file__).parent.parent / "tools" / "windows_zones.py"
_spec = importlib.util.spec_from_file_location("windows_zones_tool", TOOL)
assert _spec is not None and _spec.loader is not None
tool = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(tool)
XML = """<?xml version="1.0" encoding="UTF-8" ?>
<supplementalData><windowsZones><mapTimezones>
<mapZone other="India Standard Time" territory="001" type="Asia/Calcutta"/>
<mapZone other="India Standard Time" territory="IN" type="Asia/Calcutta"/>
<mapZone other="Greenwich Standard Time" territory="001" type="Atlantic/Reykjavik"/>
<mapZone other="Greenwich Standard Time" territory="CI" type="Africa/Abidjan"/>
<mapZone other="UTC" territory="001" type="Etc/UTC"/>
<mapZone other="UTC" territory="ZZ" type="Etc/UTC Etc/GMT"/>
</mapTimezones></windowsZones></supplementalData>
"""
TZDATA = """# version 2026e
Z Etc/UTC 0 - UTC
L Asia/Kolkata Asia/Calcutta
L Africa/Abidjan Atlantic/Reykjavik
L Etc/UTC UTC
"""
def _tables(tmp_path: Path) -> tuple[dict[str, str], dict[str, str]]:
(tmp_path / "w.xml").write_text(XML)
(tmp_path / "tzdata.zi").write_text(TZDATA)
primary, to_windows, _ = tool.read_cldr(tmp_path / "w.xml")
return tool.build(primary, to_windows, tool.read_links(tmp_path / "tzdata.zi"))
def test_a_renamed_zone_reads_as_its_new_name(tmp_path):
windows_to_iana, iana_to_windows = _tables(tmp_path)
assert windows_to_iana["India Standard Time"] == "Asia/Kolkata"
assert iana_to_windows["Asia/Kolkata"] == iana_to_windows["Asia/Calcutta"]
def test_a_merged_zone_keeps_its_name(tmp_path):
windows_to_iana, _ = _tables(tmp_path)
assert windows_to_iana["Greenwich Standard Time"] == "Atlantic/Reykjavik"
def test_links_to_a_mapped_zone_are_mapped(tmp_path):
_, iana_to_windows = _tables(tmp_path)
assert iana_to_windows["UTC"] == "UTC"
assert iana_to_windows["Etc/GMT"] == "UTC"
def test_the_module_names_its_sources(tmp_path):
text = tool.render(*_tables(tmp_path), "release-49", "abc", "2026e")
assert "CLDR release-49" in text and "sha256 abc" in text and "2026e" in text
namespace: dict[str, object] = {}
exec(compile(text, "generated", "exec"), namespace)
assert namespace["WINDOWS_TO_IANA"] == _tables(tmp_path)[0]
+78 -3
View File
@@ -1,11 +1,17 @@
"""Record what the driver's PowerShell scripts emit on a real Windows host.
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure] [--runs]
Asks for the password, runs every getter script over one WinRM connection and
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
MAC and IP addresses, host names, account names and SIDs before copying anything into
tests/.
MAC and IP addresses and host names before copying anything into tests/.
``--runs`` also records the repair runs' output (``RUNS``), one output object per
line in <run>.txt. They take up to an hour together, and two of them act on the
host: the Defender signature update and a quick scan.
"""
from __future__ import annotations
@@ -13,8 +19,29 @@ from __future__ import annotations
import argparse
import getpass
import pathlib
import time
from napalm_windows import WindowsDriver
from napalm_windows import (
WindowsDriver,
event_channels,
host_events,
host_firewall,
host_status,
login_accounts,
login_sessions,
os_users,
packages,
posture,
processes,
repairs,
scheduled_tasks,
services,
storage,
system_identity,
time_sync,
windows_features,
windows_update,
)
from napalm_windows import windows as mod
SCRIPTS = {
@@ -23,8 +50,38 @@ SCRIPTS = {
"interfaces_ip": mod._PS_INTERFACES_IP,
"arp": mod._PS_ARP,
"routes": mod._PS_ROUTES,
"services": mod._PS_SERVICES,
"services": services._PS_SERVICES,
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"disks": storage._PS_DISKS,
"storage_pools": storage._PS_STORAGE_POOLS,
"volumes": storage._PS_VOLUMES,
"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,
"login_accounts": login_accounts._PS_LOGIN_ACCOUNTS,
"login_sessions": login_sessions._PS_LOGIN_SESSIONS,
"host_firewall": host_firewall._PS_HOST_FIREWALL,
"windows_features": windows_features._PS_WINDOWS_FEATURES,
"host_events": host_events.host_events_script(time.time() - 7 * 86400),
"event_channels": event_channels._PS_EVENT_CHANNELS,
# The search takes minutes and keeps its reading under HKLM\SOFTWARE\napalm-windows,
# which the pending reading after it reads back. Nothing is installed.
"wu_search": windows_update._PS_WU_SEARCH,
"wu_pending": windows_update._PS_WU_PENDING,
"wu_history": windows_update._PS_WU_HISTORY,
"posture": posture._PS_POSTURE,
}
# Recorded only with --runs: streamed, long, and two of them change the host.
RUNS = {
"sfc_verifyonly": (repairs._PS_SFC_VERIFY, repairs.SFC_LIMIT),
"dism_scanhealth": (repairs._PS_DISM_SCAN, repairs.DISM_LIMIT),
"defender_signature_update": (repairs._PS_SIGNATURE_UPDATE, repairs.SIGNATURE_LIMIT),
"defender_quick_scan": (repairs._PS_QUICK_SCAN, repairs.QUICK_SCAN_LIMIT),
}
OUT = pathlib.Path(__file__).parent / "harvest-out"
@@ -37,6 +94,7 @@ def main() -> None:
ap.add_argument("label", help="subdirectory name, e.g. server2022 or win11")
ap.add_argument("--port", type=int, default=5986)
ap.add_argument("--insecure", action="store_true", help="skip certificate validation")
ap.add_argument("--runs", action="store_true", help="also record the repair runs (RUNS)")
args = ap.parse_args()
driver = WindowsDriver(
@@ -59,10 +117,27 @@ def main() -> None:
else:
print(f" {name}: {len(raw)} bytes")
(target / f"{name}.json").write_text(raw + "\n")
for name, (script, limit) in RUNS.items() if args.runs else ():
_record_run(driver, target, name, script, limit)
finally:
driver.close()
print(f"written to {target}")
def _record_run(
driver: WindowsDriver, target: pathlib.Path, name: str, script: str, limit: int
) -> None:
"""One repair run's output objects as the host sent them, NULs and all."""
assert driver._transport is not None
try:
lines = driver._transport.run_streaming(script, lambda _line: None, limit=limit)
except Exception as exc: # record the failure, keep harvesting
lines = []
print(f" {name}: FAILED — {exc}")
else:
print(f" {name}: {len(lines)} lines")
(target / f"{name}.txt").write_text("".join(f"{line}\n" for line in lines))
if __name__ == "__main__":
main()
+109
View File
@@ -0,0 +1,109 @@
"""Generate napalm_windows/_windows_zones.py from CLDR's windowsZones.xml and tzdata's links.
python tools/windows_zones.py windowsZones.xml /usr/share/zoneinfo/tzdata.zi \\
--cldr release-49 > napalm_windows/_windows_zones.py
windowsZones.xml is CLDR's mapping of Windows zone ids to IANA names
(https://github.com/unicode-org/cldr/blob/<release>/common/supplemental/windowsZones.xml);
tzdata.zi is the compact form of the IANA database, read for its link lines (``L target
alias``). The driver never fetches either at runtime: rerun this when a new CLDR release
adds Windows zones, and commit the result.
* ``WINDOWS_TO_IANA``: each Windows zone's territory ``001`` zone -- the one name CLDR
gives it. CLDR keeps old names (``Asia/Calcutta``, ``Europe/Kiev``); one that is a
link in tzdata to a zone CLDR does not name is replaced by that zone (``Asia/Kolkata``).
A link to a zone CLDR does name is a merge, not a rename (``Atlantic/Reykjavik`` ->
``Africa/Abidjan``), and keeps its own name.
* ``IANA_TO_WINDOWS``: every IANA name CLDR maps, in any territory, to its Windows zone;
plus each tzdata link to or from such a name that CLDR does not map itself.
"""
from __future__ import annotations
import argparse
import hashlib
import pathlib
import xml.etree.ElementTree as ET # nosec B405 - a file the developer downloaded, not input
def read_cldr(path: pathlib.Path) -> tuple[dict[str, str], dict[str, str], set[str]]:
"""``(windows -> 001 zone, every CLDR zone -> windows, all CLDR names)``."""
primary: dict[str, str] = {}
to_windows: dict[str, str] = {}
for node in ET.parse(path).iter("mapZone"): # nosec B314
windows, names = node.attrib["other"], node.attrib["type"].split()
if node.attrib["territory"] == "001":
primary[windows] = names[0]
for name in names:
if to_windows.setdefault(name, windows) != windows:
raise SystemExit(f"{name} maps to {to_windows[name]} and {windows}")
return primary, to_windows, set(to_windows)
def read_links(path: pathlib.Path) -> list[tuple[str, str]]:
"""tzdata's ``(target, alias)`` links."""
links = []
for line in path.read_text().splitlines():
if line.startswith("L "):
_, target, alias = line.split()
links.append((target, alias))
return links
def build(
primary: dict[str, str], to_windows: dict[str, str], links: list[tuple[str, str]]
) -> tuple[dict[str, str], dict[str, str]]:
cldr = set(to_windows)
renamed = {alias: target for target, alias in links if target not in cldr}
windows_to_iana = {w: renamed.get(name, name) for w, name in sorted(primary.items())}
iana_to_windows = dict(to_windows)
for target, alias in links:
if target in to_windows and alias not in iana_to_windows:
iana_to_windows[alias] = to_windows[target]
elif alias in to_windows and target not in iana_to_windows:
iana_to_windows[target] = to_windows[alias]
return windows_to_iana, dict(sorted(iana_to_windows.items()))
def render(
windows_to_iana: dict[str, str],
iana_to_windows: dict[str, str],
cldr_release: str,
cldr_sha: str,
tz_version: str,
) -> str:
lines = [
'"""Windows time zones and IANA names. Generated by tools/windows_zones.py: do not edit.',
"",
f"Source: CLDR {cldr_release}, common/supplemental/windowsZones.xml",
f"(sha256 {cldr_sha}),",
f"with the link lines of the IANA time zone database {tz_version} (tzdata.zi).",
'"""',
"",
"WINDOWS_TO_IANA: dict[str, str] = {",
*(f' "{w}": "{name}",' for w, name in windows_to_iana.items()),
"}",
"",
"IANA_TO_WINDOWS: dict[str, str] = {",
*(f' "{name}": "{w}",' for name, w in iana_to_windows.items()),
"}",
"",
]
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("windows_zones", type=pathlib.Path)
ap.add_argument("tzdata_zi", type=pathlib.Path)
ap.add_argument("--cldr", required=True, help="the CLDR release the XML is from")
args = ap.parse_args()
primary, to_windows, _ = read_cldr(args.windows_zones)
links = read_links(args.tzdata_zi)
tz_version = args.tzdata_zi.read_text().splitlines()[0].removeprefix("# version ").strip()
sha = hashlib.sha256(args.windows_zones.read_bytes()).hexdigest()
print(render(*build(primary, to_windows, links), args.cldr, sha, tz_version), end="")
if __name__ == "__main__":
main()