# Conflicts: # CHANGELOG.md # README.md # napalm_windows/windows.py # tools/harvest.py
24 KiB
napalm-windows
NAPALM driver for Windows Server 2016+ and Windows 10/11, part of the netOrk
driver family built on napalm-device-types.
Driver name: windows · Role: OSDriver · Transport: PowerShell Remoting
(PSRP) over WinRM via pypsrp.
Tested against
Not recorded yet: the fixtures under tests/fixtures/synthetic/ are the JSON the scripts
are designed to emit, not output recorded from a host.
Install
pip install napalm-windows
How it works
Every getter sends one PowerShell script. The script projects the cmdlet
results onto flat, primitive fields and ends in ConvertTo-Json, so the
Python side parses JSON, never text. All device I/O goes through a single
seam (PsrpTransport.run(script) -> str), which is what the tests replace.
One runspace pool stays open per connection, so a poll pays the WinRM handshake once.
Supported
| Method | Source |
|---|---|
get_facts |
Win32_ComputerSystem, Win32_OperatingSystem, Win32_BIOS, registry (DisplayVersion, UBR) |
get_interfaces |
Get-NetAdapter |
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 (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_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.
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.@rebootis 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, whichGet-ScheduledTaskdoes not expose.
Time sync
napalm-device-types' TimeSyncMixin; both the servers and the zone are written.
- Servers are w32time's
NtpServerin order, without their,0xflags; group policy's values (HKLM\SOFTWARE\Policies\Microsoft\W32Time\Parameters) win over the local ones.Type NoSynchas none. Written as<server>,0x8(client mode) withType NTP— whatw32tm /config /manualpeerlist /syncfromflags:manualwrites — thenw32tm /config /update; a stopped Windows Time service is started first. - Domain members that take their time from the domain hierarchy (
Type NT5DSorAllSync) 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.daemonisw32time. - 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 withSet-TimeZonefrom CLDR's mapping (windowsZones.xml, generated intonapalm_windows/_windows_zones.pybytools/windows_zones.py, never fetched at runtime). The IANA name written is kept inHKLM\SOFTWARE\napalm-windows(IanaTimeZone) and read back while the host is still in that Windows zone, soEurope/Viennareads back asEurope/Vienna. A zone with summer time switched off reads asNone; 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>byDeviceId): 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) isGet-StorageReliabilityCounterper 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 writes0for 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
-1and healthunknown: Windows calls itHealthy, which only says it is attached.WarningandUnhealthyare 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'sDefaultAccountandWDAGUtilityAccount.uidis the RID,sidthe SID;shellis empty,homethe profile folder. The last login and the failed attempts since it (BadPasswordAttempts) are the account database's, sourcesam; an account islockedwhen 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:
administratoris membership ofS-1-5-32-544;remote_desktopthat the host takes Remote Desktop logins (fDenyTSConnections, group policy first) and the account holdsSeRemoteInteractiveLogonRightwithout being denied it, through itself, a local group, or a SID every local logon carries (Everyone, Local account).groupslists 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
ttyconsoleorrdp; network logons (type 3) are not, since every WinRM and SMB connection is one. A person's account only: notDWM-norUMFD-n. An administrator's two linked logons are one session; the end is its logoff (4634, 4647).own_addressis 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_sinceis 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, raisesLoginSessionsUnavailable. - 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'sInstanceID: 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
(
DomainAuthenticatedis 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.
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.
cpuis the CPU time over the time since the start, per logical processor;memorythe working set over the visible memory;startedthe local time asps -o lstartprints it. Windows has no controlling terminal and nopsstate:ttyandstateare empty. The owner needs an elevated session; without one it is empty. PID 0 (System Idle Process) is no process. - Local accounts.
gidis 513, the primary group of every local account;homeis the profile folder, empty until the account first logs on;shellis empty. - Packages. A 32-bit and a 64-bit install of one program are two packages, told
apart by
architecture. Keys without aDisplayName,SystemComponent=1and entries with aParentKeyNameare left out. - Restart required is Windows Update's
RebootRequired(or its registry marker) or component servicing'sRebootPending.PendingFileRenameOperations,UpdateExeVolatileand a pending computer rename only make up the reason. - Automatic updates. Policy first:
NoAutoUpdate=1off,AUOptions4 on, 2, 3 and 7 off, 5 the local setting. Without a policy a client is on and a server follows its localAUOptions; 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_updatessearches the source the host is configured for -- Windows Update, or the WSUS server group policy names -- forIsInstalled=0 and IsHidden=0 and Type='Software': no drivers. A search takes minutes, so the poll never runs one. It keeps its reading underHKLM\SOFTWARE\napalm-windows\WindowsUpdate(only administrators and SYSTEM may write there), andget_available_updatesreads that back, leaving out what the host's history shows installed since. Before the first search it raisesPackageIndexMissing, 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_versionandadvisoriesare its KB articles,cvesitsCveIDs,vendor_severityitsMsrcSeverity,titleits title. A security update, a definition update or one naming CVEs issecurity; 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 tolog, 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 asnapalm-windows, which the history'srequested_byshows.get_scheduled_jobsreports these tasks as an application's, offering nothing. - History (
get_update_history):QueryHistory, newest 300 entries, one transaction each;requested_byis theClientApplicationID(UpdateOrchestrator,AutomaticUpdates,napalm-windows),errorthe 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, andrepair_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'slogas 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:
sfcwrites UTF-16 to a redirected stdout and is read as such; DISM runs with/Englishin 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-Commandfinds 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
Enable-PSRemoting once. Then either
- HTTPS (5986, default) — needs a certificate-backed HTTPS listener, or
- HTTP (5985) — set the device port to 5985. Traffic is still encrypted at message level (NTLM/Kerberos), credentials never travel in the clear.
A local administrator account additionally needs
LocalAccountTokenFilterPolicy = 1 under
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System; without it
remote UAC strips the admin token. Domain accounts are not affected.
optional_args
| Key | Default | Meaning |
|---|---|---|
port |
5986 |
WinRM port |
winrm_ssl |
port != 5985 |
force HTTPS on or off |
winrm_auth |
negotiate |
pypsrp auth protocol (negotiate, ntlm, kerberos, credssp, basic) |
ssl_verify |
True |
validate the WinRM certificate |
Development
The rules are in STANDARDS.md.
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/pytest --cov
Tests and fixtures
tests/fixtures/synthetic/ holds the JSON the scripts are designed to emit.
To record the real thing from a host:
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
Output lands in tools/harvest-out/ (gitignored); scrub it before copying
anything into tests/.
License
Apache-2.0, see LICENSE.