Author SHA1 Message Date
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
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
27 changed files with 4351 additions and 34 deletions

No files matched your search

+66
View File
@@ -6,6 +6,72 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- The host firewall (NetOrk/netork#2894): `get_host_firewall` returns the Windows
Firewall under `windows` (napalm-device-types' `WindowsFirewallDict`), with `sources`
`["windows-firewall"]` and no netfilter chains. It reads the three profiles as the
firewall applies them (on or off, default inbound and outbound action, "block all
incoming connections", whether local rules apply), every enabled rule of the active
policy with its ports, addresses, program, service, interfaces and where it comes from
(group policy included), and the profile each connected interface is in. The filters
are read in bulk, one cmdlet per kind, so a host with hundreds of rules answers in one
script rather than one query per rule. Nothing is written.
- Windows features (NetOrk/netork#2898): `get_windows_features` lists every optional
feature of the host's image with its state (enabled, disabled, absent, unknown) from
`Win32_OptionalFeature`, under the names Windows uses on clients and servers alike
(`SMB1Protocol`, `MSMQ-Server`, `IIS-WebServerRole`, `Microsoft-Hyper-V`). It is what
a CVE that needs a role or feature is held against.
- 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.
+77 -1
View File
@@ -37,13 +37,89 @@ handshake once.
| `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` |
| `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_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
| `get_host_firewall` | The Windows Firewall under `windows` (no netfilter chains): the profiles' settings in force from `HNetCfg.FwPolicy2`, `AllowLocalFirewallRules` from `Get-NetFirewallProfile`, the enabled rules of `Get-NetFirewallRule -PolicyStore ActiveStore` with every filter read in bulk and joined on `InstanceID`, and `Get-NetConnectionProfile`. See *Host firewall* |
| `get_windows_features` | `Win32_OptionalFeature`: every optional feature of the image with its state, under DISM's names (`SMB1Protocol`, `MSMQ-Server`), a server's roles included |
`running_kernel` carries the full build including the update revision
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
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.
### Host firewall
What the exposure chain holds a listening socket against (netork#2894). Read only: no
rule is ever written.
* **Profiles:** on or off, the default inbound and outbound action and "block all
incoming connections" as the firewall applies them (`HNetCfg.FwPolicy2`, group
policy over local), and whether group policy lets local rules apply.
* **Rules:** every enabled rule of the active policy (`ActiveStore`, local and group
policy merged), inbound and outbound, each with where it comes from (`local`,
`group_policy`, `dynamic`, ...). Its filters -- ports, addresses, program, service,
app package, interfaces, interface types, IPsec -- are read with one cmdlet per
filter kind (`Get-NetFirewallPortFilter -All`, ...) and joined on the rule's
`InstanceID`: one filter query per rule takes minutes on a few hundred rules.
Addresses become CIDRs (a mask as its prefix, a range as the networks covering it);
Windows' keywords (`LocalSubnet`, `RPC`) are kept in lower case. A block rule whose
filters did not all come back is left out rather than read as blocking everything.
* **Connections:** the profile of each connected interface, from its network's category
(`DomainAuthenticated` is the domain profile); None where that could not be read.
Not yet: packages, Windows Update, health metrics, Hyper-V.
See netork#300 for the plan.
## Preparing a host
+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}'"
+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",
}
+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)
+461
View File
@@ -0,0 +1,461 @@
"""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 -- 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
# 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]:
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
)
platform = path.lower().startswith("\\microsoft\\")
return _Definition(
triggers,
"triggers",
command,
"platform" if platform else "admin",
str(task.get("description") or "").strip(),
)
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")
+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"]
+16
View File
@@ -104,6 +104,22 @@ 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_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:
+52 -21
View File
@@ -26,7 +26,12 @@ 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_windows._powershell import _as_list, _ps_quote
from napalm_windows.host_firewall import WindowsHostFirewallMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
from napalm_windows.windows_features import WindowsFeaturesMixin
logger = logging.getLogger(__name__)
@@ -178,13 +183,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",
@@ -204,22 +212,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 +263,13 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(OSDriver):
class WindowsDriver(
WindowsHostFirewallMixin,
WindowsFeaturesMixin,
WindowsScheduledJobsMixin,
WindowsTimeSyncMixin,
OSDriver,
):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
@@ -369,6 +367,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 +443,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 +452,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(
@@ -520,6 +529,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)
+5 -7
View File
@@ -7,7 +7,7 @@ name = "napalm-windows"
version = "0.2.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.35.0", # TimeSyncMixin
"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
+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"}
]
}
+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
}
]
}
+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}
+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}
]
+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
+639
View File
@@ -0,0 +1,639 @@
"""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
+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"
+47 -1
View File
@@ -11,7 +11,7 @@ from unittest.mock import patch
import pytest
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.exceptions import AuthenticationError, WinRMTransportError
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from napalm_windows.transport import PowerShellError, PsrpTransport
@@ -120,6 +120,52 @@ 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 TestClose:
def test_close_closes_pool_and_connection(self, psrp):
t = _transport()
+76 -3
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):
@@ -483,3 +504,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
+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]
+11 -1
View File
@@ -14,7 +14,13 @@ import argparse
import getpass
import pathlib
from napalm_windows import WindowsDriver
from napalm_windows import (
WindowsDriver,
host_firewall,
scheduled_tasks,
time_sync,
windows_features,
)
from napalm_windows import windows as mod
SCRIPTS = {
@@ -25,6 +31,10 @@ SCRIPTS = {
"routes": mod._PS_ROUTES,
"services": mod._PS_SERVICES,
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"host_firewall": host_firewall._PS_HOST_FIREWALL,
"windows_features": windows_features._PS_WINDOWS_FEATURES,
}
OUT = pathlib.Path(__file__).parent / "harvest-out"
+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()