Author SHA1 Message Date
Christian Manivong 2b0bfac4f7 refactor(logins): keep the member and session parses within complexity 10 (NetOrk/netork#2895)
_member hands its name and kind to _member_name and _is_group;
parse_login_sessions hands the audit check to _audited_logons and the
sessions to _sessions. No change in behaviour.
2026-12-01 23:20:36 +01:00
Christian Manivong de6ab3c801 feat(logins): login accounts and console and Remote Desktop sessions (NetOrk/netork#2895)
get_login_accounts reads the host's own accounts (Get-LocalUser), their
last login and failed attempts from the account database, expiry and
lock, and whether each is an administrator (S-1-5-32-544, by SID) or may
log in over Remote Desktop (the logon right and its denial from
secedit, the host's fDenyTSConnections). groups lists the groups that
grant either, with every member, a domain's included. uid is the RID,
sid the SID. A domain controller's accounts are not read.

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

Both scripts are in tools/harvest.py.
2026-12-01 12:55:49 +01:00
31 changed files with 1811 additions and 1519 deletions

No files matched your search

+16 -28
View File
@@ -7,34 +7,22 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- The host's SMBIOS identity, what ties it to its BMC (NetOrk/netork#2888):
`get_system_identity` reads the system UUID and product serial
(`Win32_ComputerSystemProduct`), the board serial (`Win32_BaseBoard`) and the system
firmware's vendor, version and release date (`Win32_BIOS`) in one script of its own.
Vendor placeholders such as "To be filled by O.E.M." or an all-F UUID read as empty,
by napalm-device-types' rules (`clean_system_identity`).
- Running processes (NetOrk/netork#2889): `get_processes` lists them the way `ps` does --
parent, owner, CPU and memory share, virtual and resident size, start and command line
-- from `Win32_Process` and `Get-Process -IncludeUserName` in one script. A process
that exited between the two reads, or whose PID was reused in between, is left out.
- Local accounts (NetOrk/netork#2889): `get_os_users` lists the host's own accounts with
their local groups and profile folder. `uid` is the account's relative identifier
(500 for the built-in Administrator), `sid` its whole security identifier. A domain
controller, which has no local accounts, and a host without the LocalAccounts cmdlets
raise `NotImplementedError`.
- Installed software (NetOrk/netork#2890): `get_packages` lists the programs installed
for the whole machine from the Uninstall keys, the 64-bit and the 32-bit ones, each
with its publisher and architecture; `source` is `msi` or `exe`. Hidden system
components and updates listed under their product are left out. Programs installed
for one user only, and Store apps, are not read yet; nothing is installed or removed.
- Restart required and automatic updates (NetOrk/netork#2891): `get_host_status` says
the host needs a restart when Windows Update or component servicing waits for one;
pending file renames, a pending update executable and a new computer name are named
in the reason but do not count on their own. Automatic updates follow the Windows
Update policy (`NoAutoUpdate`, `AUOptions`); without one a Windows client installs on
its own and a server follows its local setting. When they last succeeded is the
latest successful installation Windows Update recorded; the system drive's size and
free space come with it. Nothing searches for updates during the reading.
- Who can log in to the host and who did, for the access review (NetOrk/netork#2895):
napalm-device-types' `get_login_accounts` and `get_login_sessions`.
- `get_login_accounts` lists the host's own accounts (`Get-LocalUser`) with their
last login and failed attempts since it from the account database (source `sam`),
password and account expiry, and whether each is locked (disabled, expired or locked
out). Each says whether it is an administrator and whether it may log in over
Remote Desktop: found by SID, so a German "Administratoren" counts, and from the
Remote Desktop logon right and its denial (`secedit /export`) with the host's
Remote Desktop setting. `groups` lists the groups granting either, with every
member, a domain's groups and accounts by name. `uid` is the RID, `sid` the SID. A
domain controller's accounts are the directory's and are not listed.
- `get_login_sessions` lists the console and Remote Desktop logons of the last seven
days from the Security log, each with its account, address, start and end; never a
network logon, so neither the driver's own WinRM connection nor SMB access shows.
`records_since` says how far back the log reaches, and a host that does not audit
logons raises `LoginSessionsUnavailable` rather than reporting nobody.
- 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
+32 -28
View File
@@ -42,12 +42,9 @@ handshake once.
| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones |
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
| `get_system_identity` | `Win32_ComputerSystemProduct` (UUID, serial), `Win32_BaseBoard`, `Win32_BIOS`; placeholders empty (napalm-device-types' `clean_system_identity`). See *Host basics* |
| `get_processes` | `Win32_Process` joined with `Get-Process -IncludeUserName` by PID and start, shaped like `ps` |
| `get_os_users` | `Get-LocalUser`, `Get-LocalGroup` + `Get-LocalGroupMember` (ADSI fallback), `Win32_UserProfile`; the RID as `uid`, the SID as `sid` |
| `get_packages` | The machine-wide Uninstall keys, native and `WOW6432Node`; no per-user installs, no Store apps, nothing installed |
| `get_host_status` | `Microsoft.Update.SystemInfo`, the registry's restart markers, the Windows Update policy and history, the system drive |
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
| `get_login_accounts` | `Get-LocalUser`, `Win32_UserProfile`, `WinNT:` (`BadPasswordAttempts`, `IsAccountLocked`, group members), `secedit /export /areas USER_RIGHTS`, `fDenyTSConnections`. See *Logins* |
| `get_login_sessions` | Security log 4624 (logon types 2, 10, 11), 4634/4647, bounded to seven days on the host. See *Logins* |
`running_kernel` carries the full build including the update revision
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
@@ -102,31 +99,38 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
zone with summer time switched off reads as `None`; writing the zone switches it
back on.
### Host basics
### Logins
* **Identity.** Windows decodes the SMBIOS system UUID the way dmidecode does; the
release date is CIM's midnight UTC, read as that day.
* **Processes.** `cpu` is the CPU time over the time since the start, per logical
processor; `memory` the working set over the visible memory; `started` the local time
as `ps -o lstart` prints it. Windows has no controlling terminal and no `ps` state:
`tty` and `state` are empty. The owner needs an elevated session; without one it is
empty. PID 0 (System Idle Process) is no process.
* **Local accounts.** `gid` is 513, the primary group of every local account; `home` is
the profile folder, empty until the account first logs on; `shell` is empty.
* **Packages.** A 32-bit and a 64-bit install of one program are two packages, told
apart by `architecture`. Keys without a `DisplayName`, `SystemComponent=1` and
entries with a `ParentKeyName` are left out.
* **Restart required** is Windows Update's `RebootRequired` (or its registry marker) or
component servicing's `RebootPending`. `PendingFileRenameOperations`,
`UpdateExeVolatile` and a pending computer rename only make up the reason.
* **Automatic updates.** Policy first: `NoAutoUpdate=1` off, `AUOptions` 4 on, 2, 3
and 7 off, 5 the local setting. Without a policy a client is on and a server follows
its local `AUOptions`; a server with neither reads as unknown. The last success is the
latest successful installation Windows Update recorded (its history, the AutoUpdate
result, the older registry result); the interval is 31 days, the cadence of the
monthly cumulative update.
napalm-device-types' login readings, for the access review (NetOrk/netork#2895). Both
are read-only, one script each, and take an administrator.
Not yet: Windows Update, health metrics, Hyper-V.
* **Accounts** are the host's own (`Get-LocalUser`; without it, not supported), not the
system's `DefaultAccount` and `WDAGUtilityAccount`. `uid` is the RID, `sid` the SID;
`shell` is empty, `home` the profile folder. The last login and the failed attempts
since it (`BadPasswordAttempts`) are the account database's, source `sam`; an account
is `locked` when disabled, expired or locked out. A domain controller's accounts are
the directory's and are not read.
* **Administrators and Remote Desktop** go by SID, so a German host's "Administratoren"
is found: `administrator` is membership of `S-1-5-32-544`; `remote_desktop` that the
host takes Remote Desktop logins (`fDenyTSConnections`, group policy first) and the
account holds `SeRemoteInteractiveLogonRight` without being denied it, through
itself, a local group, or a SID every local logon carries (Everyone, Local account).
`groups` lists the groups that grant either, with every member as the host names it,
a domain's groups included. secedit's export goes to a file under
`%SystemRoot%\Temp`, removed at once.
* **Sessions** are logon events 4624 of type 2 (console), 10 (Remote Desktop) and 11
(cached, at the console) of the last seven days, the newest 1000, as `tty` `console`
or `rdp`; network logons (type 3) are not, since every WinRM and SMB connection is
one. A person's account only: not `DWM-n` or `UMFD-n`. An administrator's two linked
logons are one session; the end is its logoff (4634, 4647). `own_address` is the
address of the reading's own WinRM logon, found by its logon ID, else the one client
connected to WinRM; its sessions are left out. `records_since` is the Security log's
oldest event: the log rotates by size, so a login before it is unknown. A log that
holds no logon, not even the reading's own, raises `LoginSessionsUnavailable`.
* **Not read:** OpenSSH for Windows logins and the Remote Desktop session manager's own
log (`TerminalServices-LocalSessionManager`); the domain's accounts.
Not yet: packages, Windows Update, health metrics, Hyper-V.
See netork#300 for the plan.
## Preparing a host
-18
View File
@@ -1,18 +0,0 @@
"""One reading script's JSON object, which the host readings of this driver share."""
from __future__ import annotations
import json
from typing import Any
def json_object(out: str, what: str) -> dict[str, Any]:
"""*out*, a script's ``ConvertTo-Json`` of one object, parsed.
:raises ValueError: when it is empty or no object, naming *what* was read.
"""
out = out.strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError(f"the {what} reading came back empty")
return raw
-28
View File
@@ -1,28 +0,0 @@
"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891).
One mixin made of one module per reading, so the driver names a single base:
* :mod:`napalm_windows.system_identity` -- ``get_system_identity``
* :mod:`napalm_windows.processes` -- ``get_processes``
* :mod:`napalm_windows.os_users` -- ``get_os_users``
* :mod:`napalm_windows.packages` -- ``get_packages``
* :mod:`napalm_windows.host_status` -- ``get_host_status``
"""
from __future__ import annotations
from napalm_windows.host_status import WindowsHostStatusMixin
from napalm_windows.os_users import WindowsOsUsersMixin
from napalm_windows.packages import WindowsPackagesMixin
from napalm_windows.processes import WindowsProcessesMixin
from napalm_windows.system_identity import WindowsSystemIdentityMixin
class WindowsHostBasicsMixin(
WindowsSystemIdentityMixin,
WindowsProcessesMixin,
WindowsOsUsersMixin,
WindowsPackagesMixin,
WindowsHostStatusMixin,
):
"""The readings napalm-linux has as a matter of course; each module documents its own."""
-230
View File
@@ -1,230 +0,0 @@
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
:class:`WindowsHostStatusMixin` gives the driver napalm-device-types' ``get_host_status``
(``HostStatusDict``) in one script. Each part is read on its own -- a COM object that
does not answer over WinRM leaves the rest standing -- and nothing searches for updates:
that is the update reading's, and too slow for a poll.
**Restart required** is what Windows says about its own updates:
* Windows Update's ``Microsoft.Update.SystemInfo.RebootRequired``, and its registry
marker ``WindowsUpdate\\Auto Update\\RebootRequired`` where the COM object did not
answer;
* component-based servicing's ``RebootPending`` (features, roles, servicing stack).
Other markers only explain: ``PendingFileRenameOperations``, which antivirus and
installers set routinely and which would keep the flag up for days, ``UpdateExeVolatile``
and a new computer name taking effect at the next restart. They make up
``reboot_reason`` with the two above, and a host with only them needs no restart.
**Automatic updates** follow the policy (``HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\
WindowsUpdate\\AU``): ``NoAutoUpdate=1`` is off; ``AUOptions`` 4 installs on its own,
2, 3 and 7 only notify or download; 5 leaves it to the local setting. Without a policy
Windows 10 and 11 install on their own, and ignore the local ``AUOptions`` an upgrade may
have left; a Windows Server follows its local setting (``sconfig``), and without one the
answer is None: what each Server release does then is not established.
**When they last succeeded** is the latest successful installation Windows Update knows
of, whoever started it: its history's last 50 entries, the ``Microsoft.Update.AutoUpdate``
result and the older registry result (``Auto Update\\Results\\Install``), whichever is
latest. Windows has something to install every month -- the cumulative update -- so
automatic updates are meant to have installed something within 31 days
(``auto_updates_interval``); on Linux that is the timer's day.
**Filesystems** are the system drive's size and free space, where updates unpack.
"""
from __future__ import annotations
import calendar
import time
from typing import TYPE_CHECKING, Any
from napalm_device_types.models import FilesystemUsageDict, HostStatusDict
from napalm_windows._powershell import _as_list
from napalm_windows._reading import json_object
_AU_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
_AU_LOCAL = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
_CBS = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"
_SESSION_MANAGER = r"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager"
_COMPUTER_NAME = r"HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName"
# WUA's dates are UTC with no kind; IUpdateHistoryEntry.Operation 1 is an installation,
# ResultCode 2 succeeded and 3 succeeded with errors.
_PS_HOST_STATUS = rf"""
$ErrorActionPreference = 'Stop'
function V($path, $name) {{
$item = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue
if ($item) {{ $item.$name }}
}}
function Utc($t) {{
if ($t) {{ ([DateTimeOffset][DateTime]::SpecifyKind($t, 'Utc')).ToUnixTimeSeconds() }}
}}
$wu = $null
try {{ $wu = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired }} catch {{ }}
$installs = $null
try {{
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
$count = $searcher.GetTotalHistoryCount()
$installs = @(if ($count -gt 0) {{
$searcher.QueryHistory(0, [Math]::Min($count, 50)) | Where-Object {{
$_.Operation -eq 1 -and ($_.ResultCode -eq 2 -or $_.ResultCode -eq 3)
}} | ForEach-Object {{ Utc $_.Date }}
}})
}} catch {{ }}
$au = $null
try {{
$results = (New-Object -ComObject Microsoft.Update.AutoUpdate).Results
$au = Utc $results.LastInstallationSuccessDate
}} catch {{ }}
$drive = $null
try {{
$disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'"
if ($disk) {{
$drive = [pscustomobject]@{{
drive = [string]$disk.DeviceID; size = [int64]$disk.Size; free = [int64]$disk.FreeSpace
}}
}}
}} catch {{ }}
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{{
wu_reboot_required = $wu
cbs_reboot_pending = Test-Path -LiteralPath '{_CBS}\RebootPending'
wu_reboot_key = Test-Path -LiteralPath '{_AU_LOCAL}\RebootRequired'
file_renames = [bool](V '{_SESSION_MANAGER}' 'PendingFileRenameOperations')
update_exe = [string](V 'HKLM:\SOFTWARE\Microsoft\Updates' 'UpdateExeVolatile')
computer_name = [string](V '{_COMPUTER_NAME}\ComputerName' 'ComputerName')
active_name = [string](V '{_COMPUTER_NAME}\ActiveComputerName' 'ComputerName')
no_auto_update = [string](V '{_AU_POLICY}' 'NoAutoUpdate')
au_options = [string](V '{_AU_POLICY}' 'AUOptions')
local_au_options = [string](V '{_AU_LOCAL}' 'AUOptions')
product_type = [int](Get-CimInstance -ClassName Win32_OperatingSystem).ProductType
installs = $installs
au_last_install = $au
legacy_last_install = [string](V '{_AU_LOCAL}\Results\Install' 'LastSuccessTime')
system_drive = $drive
}})
"""
#: ``AUOptions``: 2 notify, 3 download and notify, 4 install on a schedule, 7 (Server)
#: download, notify to install and to restart; 1 is the older "never check".
_AU_OPTIONS = {"1": False, "2": False, "3": False, "4": True, "7": False}
#: ``Win32_OperatingSystem.ProductType`` of a client; 2 and 3 are servers.
_WORKSTATION = 1
#: How often a Windows host has something to install: the monthly cumulative update.
MONTHLY = 31 * 86400
def _marker(raw: dict[str, Any], key: str) -> bool:
return raw.get(key) is True
#: The markers that explain a restart, in the order they are named, each with its words.
_REASONS = (
(
("wu_reboot_required", "wu_reboot_key"),
"Windows Update needs a restart to finish installing updates",
),
(("cbs_reboot_pending",), "component-based servicing has a restart pending"),
(
("file_renames",),
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
),
)
def _rename(raw: dict[str, Any]) -> str | None:
"""The new computer name a restart takes effect with, if there is one."""
new, active = str(raw.get("computer_name") or ""), str(raw.get("active_name") or "")
if new and active and new.lower() != active.lower():
return f"the computer takes its new name {new} at the next restart"
return None
def _restart_reasons(raw: dict[str, Any]) -> list[str]:
reasons = [text for keys, text in _REASONS if any(_marker(raw, key) for key in keys)]
if str(raw.get("update_exe") or "0") != "0":
reasons.append("an update waits for a restart (UpdateExeVolatile)")
rename = _rename(raw)
return [*reasons, rename] if rename else reasons
def _restart_required(raw: dict[str, Any]) -> bool:
"""Windows Update or component servicing waits for a restart; see the module."""
return any(
_marker(raw, key) for key in ("wu_reboot_required", "wu_reboot_key", "cbs_reboot_pending")
)
def _auto_updates(raw: dict[str, Any]) -> bool | None:
"""Whether the host installs updates on its own; see the module."""
if str(raw.get("no_auto_update") or "") == "1":
return False
policy = _AU_OPTIONS.get(str(raw.get("au_options") or ""))
if policy is not None:
return policy
if int(raw.get("product_type") or 0) == _WORKSTATION:
return True
return _AU_OPTIONS.get(str(raw.get("local_au_options") or ""))
def _registry_time(value: Any) -> int | None:
"""``Results\\Install``'s ``LastSuccessTime``, ``YYYY-MM-DD HH:MM:SS`` in UTC."""
try:
return calendar.timegm(time.strptime(str(value or ""), "%Y-%m-%d %H:%M:%S"))
except ValueError:
return None
def _last_success(raw: dict[str, Any]) -> int | None:
"""The latest successful installation any of the three sources knows of."""
known = [*_as_list(raw.get("installs")), raw.get("au_last_install")]
known.append(_registry_time(raw.get("legacy_last_install")))
times = [int(t) for t in known if isinstance(t, int | float) and t > 0]
return max(times, default=None)
def _filesystems(raw: dict[str, Any]) -> list[FilesystemUsageDict] | None:
drive = raw.get("system_drive")
if not isinstance(drive, dict):
return None
total, free = int(drive.get("size") or 0), int(drive.get("free") or 0)
return [
{
"mountpoint": f"{drive.get('drive') or ''}\\",
"total": total,
"used": total - free,
"available": free,
}
]
def parse_host_status(raw: dict[str, Any]) -> HostStatusDict:
"""``_PS_HOST_STATUS``'s JSON as the host status; see the module."""
reasons = _restart_reasons(raw)
auto = _auto_updates(raw)
return {
"reboot_required": _restart_required(raw),
"reboot_reason": "; ".join(reasons) or None,
"auto_updates": auto,
"auto_updates_last_success": _last_success(raw),
"auto_updates_interval": MONTHLY if auto else None,
"filesystems": _filesystems(raw),
}
class WindowsHostStatusMixin:
"""``get_host_status`` from Windows Update and the registry; the driver carries the
script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_host_status(self) -> HostStatusDict:
"""Whether the host needs a restart and installs updates on its own; see the module.
:raises ValueError: when the reading came back empty.
"""
return parse_host_status(json_object(self._run_raw(_PS_HOST_STATUS), "host status"))
+424
View File
@@ -0,0 +1,424 @@
"""Who can log in to a Windows host, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginAccountsMixin` fills napalm-device-types' ``get_login_accounts``
reading (``LoginAccountsDict``) from one script, read-only:
- **The accounts** are the host's own, ``Get-LocalUser`` (probed with ``Get-Command``
first: without it the reading is not supported). ``DefaultAccount`` and
``WDAGUtilityAccount`` (RIDs 503 and 504) are the system's and are left out, as Linux
leaves out its system accounts. ``uid`` is the RID, the SID's last part, and ``sid``
the whole SID. ``home`` is the profile's folder (``Win32_UserProfile``); Windows has no
login shell, so ``shell`` is empty.
- **The last login** is the account database's (``LastLogon``), source ``sam``; it knows
no address or terminal.
- **Lock and expiry:** an account is ``locked`` when it is disabled, expired or locked out
(``IsAccountLocked`` of the ``WinNT:`` provider); the password's last change and expiry
are ``Get-LocalUser``'s. A password that never expires has no ``PasswordExpires``.
- **The failed attempts since the last login** are ``BadPasswordAttempts`` (``WinNT:``),
which a successful login resets, source ``sam``.
- **Administrators and Remote Desktop** go by SID, never by name: the Administrators
group is ``S-1-5-32-544`` in every language ("Administratoren"). Its members, and those
of every local group that holds or is denied the right to log in through Remote Desktop
Services (``SeRemoteInteractiveLogonRight``, ``SeDenyRemoteInteractiveLogonRight``, from
``secedit /export``), are read through ``WinNT:``, a domain's groups and accounts by
name. An account may log in at a remote desktop when the host takes such logins
(``fDenyTSConnections``, group policy's first), one of its SIDs holds the right and
none is denied it. Its SIDs are its own, those every local account's logon carries
(Everyone, Authenticated Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account)
and the local groups it or one of those is a member of.
- **A domain controller** has no accounts of its own: they are the directory's, reviewed
there. Its accounts are not read; its groups are.
Each part that fails leaves its fields ``None`` (not read), never "no"; the script's
``errors`` say which.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_accounts import (
LoginAccountDict,
LoginAccountsDict,
LoginGroupDict,
LoginGroupMemberDict,
)
logger = logging.getLogger(__name__)
#: The account database: where the last logins and the failed attempts come from.
SOURCE = "sam"
ADMINISTRATORS = "S-1-5-32-544"
REMOTE_DESKTOP_USERS = "S-1-5-32-555"
#: The system's own accounts: DefaultAccount, WDAGUtilityAccount.
_SYSTEM_RIDS = frozenset({503, 504})
#: Win32_ComputerSystem.DomainRole of a backup and a primary domain controller.
_DOMAIN_CONTROLLER = 4
#: The SIDs every local account's remote desktop logon carries: Everyone, Authenticated
#: Users, INTERACTIVE, REMOTE INTERACTIVE LOGON, Local account.
_LOGON_SIDS = frozenset({"S-1-1-0", "S-1-5-11", "S-1-5-4", "S-1-5-14", "S-1-5-113"})
#: Local account and member of the Administrators group.
_LOCAL_ADMIN = "S-1-5-114"
#: The SIDs of a domain's or the host's own accounts and groups, and of Entra ID's; any
#: other SID is a principal of the host itself (Everyone, INTERACTIVE, the BUILTIN groups).
_ACCOUNT_SIDS = ("S-1-5-21-", "S-1-12-")
_PS_LOGIN_ACCOUNTS = r"""
$ErrorActionPreference = 'Stop'
$errors = @()
$tsKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
$tsPolicy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
$rdpRight = 'SeRemoteInteractiveLogonRight'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function V($path, $name) {
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
if ($item) { [string]$item.$name }
}
function Prop($o, $name) { $o.GetType().InvokeMember($name, 'GetProperty', $null, $o, $null) }
function Sid($value) { New-Object Security.Principal.SecurityIdentifier $value }
function UserFlag($name, $prop) {
try {
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',user')
$entry.psbase.InvokeGet($prop)
} catch { $null }
}
function GroupMember($m) {
$bytes = $null
try { $bytes = [byte[]](Prop $m 'objectSid') } catch { }
$sid = $null
if ($bytes) { $sid = [Security.Principal.SecurityIdentifier]::new($bytes, 0).Value }
[pscustomobject]@{
path = [string](Prop $m 'ADsPath')
class = [string](Prop $m 'Class')
sid = $sid
}
}
function LocalGroup($sid) {
$account = (Sid $sid).Translate([Security.Principal.NTAccount]).Value
$domain, $name = $account.Split('\', 2)
if ($null -eq $name) { return }
if ($domain -ne 'BUILTIN' -and $domain -ne $env:COMPUTERNAME) { return }
$entry = [ADSI]('WinNT://' + $env:COMPUTERNAME + '/' + $name + ',group')
[pscustomobject]@{
sid = $sid
name = $name
members = @($entry.psbase.Invoke('Members') | ForEach-Object { GroupMember $_ })
}
}
function Holders($text) { @($text.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
function Rights {
$file = 'Temp\napalm-windows-' + [guid]::NewGuid().ToString('N') + '.inf'
$cfg = Join-Path $env:SystemRoot $file
try {
$null = cmd.exe /c ('secedit /export /areas USER_RIGHTS /cfg ' + $cfg + ' 2>&1')
if (-not (Test-Path -LiteralPath $cfg)) { return }
$allow = @(); $deny = @()
foreach ($line in Get-Content -LiteralPath $cfg) {
if ($line -match '^\s*(Se\w+)\s*=\s*(.*)$') {
if ($Matches[1] -eq $rdpRight) { $allow = Holders $Matches[2] }
if ($Matches[1] -eq ('SeDeny' + $rdpRight)) { $deny = Holders $Matches[2] }
}
}
[pscustomobject]@{ allow = $allow; deny = $deny }
} finally { Remove-Item -LiteralPath $cfg -ErrorAction SilentlyContinue }
}
$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
$homes = @{}
try {
Get-CimInstance -ClassName Win32_UserProfile |
ForEach-Object { $homes[[string]$_.SID] = [string]$_.LocalPath }
} catch { $errors += 'profiles: ' + $_ }
$users = $null
if ($role -ge 4) { $users = @() }
elseif (Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue) {
$users = @(Get-LocalUser | ForEach-Object {
$sid = [string]$_.SID.Value
[pscustomobject]@{
name = $_.Name
sid = $sid
enabled = [bool]$_.Enabled
home = $homes[$sid]
last_logon = Ms $_.LastLogon
password_last_set = Ms $_.PasswordLastSet
password_expires = Ms $_.PasswordExpires
account_expires = Ms $_.AccountExpires
bad_passwords = UserFlag $_.Name 'BadPasswordAttempts'
locked_out = UserFlag $_.Name 'IsAccountLocked'
}
})
}
$rights = $null
try { $rights = Rights } catch { $errors += 'rights: ' + $_ }
$wanted = @('S-1-5-32-544', 'S-1-5-32-555')
if ($rights) {
$wanted += @(@($rights.allow) + @($rights.deny) | Where-Object { $_.StartsWith('*') } |
ForEach-Object { $_.Substring(1) })
}
$groups = @(foreach ($sid in @($wanted | Select-Object -Unique)) {
try { LocalGroup $sid } catch { $errors += 'group ' + $sid + ': ' + $_ }
})
[pscustomobject]@{
computer = $env:COMPUTERNAME
domain_role = $role
admin = [bool]$me.IsInRole((Sid 'S-1-5-32-544'))
now = Ms (Get-Date)
users = $users
groups = $groups
rights = $rights
rdp_deny = V $tsKey 'fDenyTSConnections'
rdp_deny_policy = V $tsPolicy 'fDenyTSConnections'
errors = $errors
} | ConvertTo-Json -Compress -Depth 6
"""
def _iso(ms: Any) -> str | None:
"""Milliseconds since the epoch as ISO 8601 in UTC; None for none."""
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _date(ms: Any) -> str | None:
iso = _iso(ms)
return None if iso is None else iso[:10]
def _rid(sid: str) -> int | None:
try:
return int(sid.rsplit("-", 1)[1])
except (IndexError, ValueError):
return None
def _local(sid: str | None, domain: str | None, computer: str, machine: str | None) -> bool | None:
"""Whether a member is the host's own: by its SID where it says, else by its path."""
if sid and not sid.upper().startswith(_ACCOUNT_SIDS):
return True
if sid and machine:
return sid.rsplit("-", 1)[0].upper() == machine
return None if domain is None else domain.upper() == computer.upper()
def _member_name(parts: list[str], sid: str | None) -> tuple[str, str | None]:
"""The member's name as ``DOMAIN\\name`` and its domain; a bare SID has none."""
if len(parts) >= 2:
return f"{parts[-2]}\\{parts[-1]}", parts[-2]
return (parts[0] if parts else str(sid or "")), None
def _is_group(raw: dict[str, Any]) -> bool | None:
kind = str(raw.get("class") or "").lower()
return {"group": True, "user": False}.get(kind)
def _member(raw: dict[str, Any], computer: str, machine: str | None) -> LoginGroupMemberDict:
"""A ``WinNT:`` member: ``WinNT://DOMAIN/name``, ``WinNT://WORKGROUP/HOST/name`` for
the host's own, ``WinNT://S-1-5-…`` for a SID the host can no longer resolve."""
parts = [p for p in str(raw.get("path") or "").removeprefix("WinNT://").split("/") if p]
sid = str(raw.get("sid") or "") or None
name, domain = _member_name(parts, sid)
return {
"name": name,
"sid": sid,
"local": _local(sid, domain, computer, machine),
"group": _is_group(raw),
}
class _Rights:
"""Who holds and who is denied a remote desktop login; None where not read."""
def __init__(self, raw: dict[str, Any]) -> None:
rights = raw.get("rights")
self.read = isinstance(rights, dict)
holders = rights if isinstance(rights, dict) else {}
self.allow = {h.lstrip("*").upper() for h in _as_list(holders.get("allow"))}
self.deny = {h.lstrip("*").upper() for h in _as_list(holders.get("deny"))}
value = raw.get("rdp_deny_policy")
value = raw.get("rdp_deny") if value in (None, "") else value
self.enabled: bool | None = None if value in (None, "") else str(value).strip() == "0"
def holds(self, names: set[str]) -> bool | None:
"""Whether one of *names* (SIDs, account names) may log in at a remote desktop."""
if self.enabled is False:
return False
if self.enabled is None or not self.read:
return None
names = {n.upper() for n in names}
return bool(names & self.allow) and not names & self.deny
class _Groups:
"""The local groups read, by SID, with their members' SIDs."""
def __init__(self, raw: dict[str, Any]) -> None:
self.raw = [g for g in _as_list(raw.get("groups")) if isinstance(g, dict) and g.get("sid")]
self.members = {
str(g["sid"]).upper(): {
str(m.get("sid")).upper() for m in _as_list(g.get("members")) if m.get("sid")
}
for g in self.raw
}
def of(self, sid: str) -> set[str]:
"""The SIDs a local account's remote desktop logon carries."""
own = {sid.upper(), *_LOGON_SIDS}
groups = {g for g, members in self.members.items() if members & own}
extra = {_LOCAL_ADMIN} if ADMINISTRATORS in groups else set()
return own | groups | extra
def administrator(self, sid: str) -> bool | None:
if ADMINISTRATORS not in self.members:
return None
return ADMINISTRATORS in self.of(sid)
def _locked(user: dict[str, Any], now: Any) -> bool | None:
expires = user.get("account_expires")
if user.get("enabled") is False:
return True
if isinstance(expires, int | float) and isinstance(now, int | float) and expires <= now:
return True
locked_out = user.get("locked_out")
return locked_out if isinstance(locked_out, bool) else None
def _failed(user: dict[str, Any]) -> int | None:
value = user.get("bad_passwords")
return value if isinstance(value, int) and not isinstance(value, bool) else None
def _password_expires(user: dict[str, Any]) -> str | None:
"""The date, or "never" for a password set that never expires; None when not set."""
expires = _date(user.get("password_expires"))
if expires is not None:
return expires
return "never" if user.get("password_last_set") is not None else None
def _account(
user: dict[str, Any], rid: int, raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> LoginAccountDict:
sid = str(user["sid"])
last = _iso(user.get("last_logon"))
changed = _date(user.get("password_last_set"))
return {
"name": str(user.get("name") or ""),
"uid": rid,
"home": str(user.get("home") or ""),
"shell": "",
"last_login": last,
"last_login_from": None,
"last_login_port": None,
"last_login_source": SOURCE if last else None,
"password": "set" if changed else None,
"password_changed": changed,
"password_expires": _password_expires(user),
"account_expires": _date(user.get("account_expires")) or "never",
"locked": _locked(user, raw.get("now")),
"failed_logins": _failed(user),
"failed_logins_capped": False,
"sid": sid,
"administrator": groups.administrator(sid),
"remote_desktop": rights.holds(groups.of(sid) | {str(user.get("name") or "")}),
}
def _accounts(
users: Iterable[Any], raw: dict[str, Any], groups: _Groups, rights: _Rights
) -> list[LoginAccountDict]:
accounts = []
for user in users:
rid = _rid(str(user.get("sid") or "")) if isinstance(user, dict) else None
if rid is not None and rid not in _SYSTEM_RIDS:
accounts.append(_account(user, rid, raw, groups, rights))
return accounts
def _grants(sid: str, rights: _Rights) -> list[str]:
grants = ["administrator"] if sid.upper() == ADMINISTRATORS else []
if rights.holds({sid}):
grants.append("remote_desktop")
return grants
def _machine(users: Iterable[Any]) -> str | None:
"""The host's own SID, its accounts' SIDs without the RID; None without accounts."""
for user in users:
sid = str(user.get("sid") or "") if isinstance(user, dict) else ""
if sid.upper().startswith("S-1-5-21-"):
return sid.rsplit("-", 1)[0].upper()
return None
def _login_groups(raw: dict[str, Any], groups: _Groups, rights: _Rights) -> list[LoginGroupDict]:
computer = str(raw.get("computer") or "")
machine = _machine(_as_list(raw.get("users")))
found: list[LoginGroupDict] = []
for group in groups.raw:
grants = _grants(str(group["sid"]), rights)
if grants:
found.append(
{
"name": str(group.get("name") or ""),
"sid": str(group["sid"]),
"grants": grants,
"members": [
_member(m, computer, machine) for m in _as_list(group.get("members"))
],
}
)
return found
def parse_login_accounts(raw: dict[str, Any]) -> LoginAccountsDict:
"""What :data:`_PS_LOGIN_ACCOUNTS` emitted, as napalm-device-types' reading.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
"""
for error in _as_list(raw.get("errors")):
logger.info("login accounts: part not read: %s", error)
users = raw.get("users")
if users is None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER:
raise NotImplementedError("Get-LocalUser is not available on this host")
groups, rights = _Groups(raw), _Rights(raw)
accounts = _accounts(_as_list(users), raw, groups, rights)
read = users is not None and int(raw.get("domain_role") or 0) < _DOMAIN_CONTROLLER
failures = any(a["failed_logins"] is not None for a in accounts)
return {
"accounts": accounts,
"login_sources": [SOURCE] if read else [],
"failed_logins_source": SOURCE if failures else None,
"privileged": raw.get("admin") is True,
"groups": _login_groups(raw, groups, rights),
}
class WindowsLoginAccountsMixin:
"""``get_login_accounts`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_accounts(self) -> LoginAccountsDict:
"""Every account of the host and who can administer it or log in at a remote
desktop, in napalm-device-types' ``LoginAccountsDict``; see the module.
:raises NotImplementedError: when the host has no ``Get-LocalUser``.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_ACCOUNTS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login account reading came back empty")
return parse_login_accounts(raw)
+265
View File
@@ -0,0 +1,265 @@
"""The logins a Windows host recorded, at its console and over Remote Desktop
(NetOrk/netork#2895).
:class:`WindowsLoginSessionsMixin` fills napalm-device-types' ``get_login_sessions``
reading (``LoginSessionsDict``) from the Security event log, in one script, read-only:
- **The logons** are event 4624 of the last :data:`SESSION_WINDOW_DAYS` days, bounded on
the host (``timediff``), the newest :data:`SESSIONS_READ`: logon type 2 (at the
console), 10 (Remote Desktop) and 11 (at the console with cached credentials), as
``tty`` ``console`` or ``rdp``. Not type 3 (network): every SMB access and every WinRM
connection is one, this reading's own included; nor 7, an unlock of a session already
read. Only a person's account counts -- a SID of the host, a domain (``S-1-5-21-``) or
Entra ID (``S-1-12-``) -- not the window manager's or the font driver's (``DWM-1``,
``UMFD-0``). An administrator's logon is two events, a full and a filtered token
linked to each other (``TargetLinkedLogonId``): one session.
- **The end** is the logoff of the logon (4634, or 4647 when the user logged off). The
account is ``DOMAIN\\name``, the host's own accounts by name alone. The address is the
event's ``IpAddress``; a console logon's loopback is none.
- **The reading's own address** is that of its own WinRM logon: the session's logon ID
(``Win32_SessionProcess``, else the logon SID ``S-1-5-5-X-Y`` of its token) names its
4624 event. Where that event has no address, the one client connected to WinRM's ports
(``Get-NetTCPConnection``); several, none. Remote Desktop sessions from it are left out,
as on Linux the reading's own SSH sessions are.
- **Coverage:** the Security log rotates by size, often within days. ``records_since`` is
its oldest event, so a login before it is unknown rather than absent. A host that holds
not even this reading's own logon and no other in the window does not audit logons:
:class:`LoginSessionsUnavailable`, never "nobody logged in".
``Get-WinEvent`` answers no match with an error (``NoMatchingEventsFound``); the script
takes that for none. Reading the Security log takes an administrator.
"""
from __future__ import annotations
import ipaddress
import json
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types.login_sessions import (
SESSION_WINDOW_DAYS,
SESSIONS_READ,
LoginSessionsUnavailable,
session_address,
)
from napalm_windows._powershell import _as_list
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
from napalm_device_types.login_sessions import LoginSessionDict, LoginSessionsDict
#: Logon type → terminal: at the console, Remote Desktop, at the console with cached
#: credentials.
LOGON_TYPES = {"2": "console", "10": "rdp", "11": "console"}
#: The SIDs of a person's account: the host's or a domain's, and Entra ID's.
_PERSON_SIDS = ("S-1-5-21-", "S-1-12-")
_DAY_MS = 86_400_000
_PS_SESSIONS_TEMPLATE = r"""
$ErrorActionPreference = 'Stop'
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
function Events($filter, $max, [switch]$Oldest) {
try { Get-WinEvent -LogName Security -FilterXPath $filter -MaxEvents $max -Oldest:$Oldest }
catch { if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } }
}
function P($e, $i) { if ($e.Properties.Count -gt $i) { [string]$e.Properties[$i].Value } }
function Logon($t) { "Data[@Name='LogonType']='" + $t + "'" }
function Query($id, $data) {
$within = 'TimeCreated[timediff(@SystemTime) <= __WINDOW_MS__]'
$system = "*[System[EventID=" + $id + " and " + $within + "]"
if ($data) { $system + " and EventData[" + $data + "]]" } else { $system + "]" }
}
$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)
$ownId = $null
try {
$query = "ASSOCIATORS OF {Win32_Process.Handle='" + $PID + "'}" +
" WHERE AssocClass=Win32_SessionProcess"
$session = @(Get-CimInstance -Query $query)
if ($session.Count -gt 0) { $ownId = [uint64]$session[0].LogonId }
} catch { }
if ($null -eq $ownId) {
$groups = [Security.Principal.WindowsIdentity]::GetCurrent().Groups
$logonSid = @($groups | Where-Object { $_.Value -like 'S-1-5-5-*' })
if ($logonSid.Count -gt 0) {
$parts = $logonSid[0].Value.Split('-')
$ownId = ([uint64]$parts[4] -shl 32) + [uint64]$parts[5]
}
}
$canary = $null; $ownIp = $null
if ($null -ne $ownId) {
$mine = "Data[@Name='TargetLogonId']='" + ('0x{0:x}' -f $ownId) + "'"
$within = 'TimeCreated[timediff(@SystemTime) <= __DAY_MS__]'
$own = @(Events ("*[System[EventID=4624 and " + $within + "] and EventData[" + $mine + "]]") 1)
$canary = $own.Count -gt 0
if ($canary) { $ownIp = P $own[0] 18 }
}
$peers = @()
try {
$winrm = Get-NetTCPConnection -State Established -LocalPort 5985, 5986 `
-ErrorAction SilentlyContinue
$peers = @($winrm | ForEach-Object { [string]$_.RemoteAddress } | Sort-Object -Unique)
} catch { }
$logons = @(Events (Query 4624 $types) __READ__ | ForEach-Object {
[pscustomobject]@{
t = Ms $_.TimeCreated; sid = P $_ 4; user = P $_ 5; domain = P $_ 6
id = P $_ 7; type = P $_ 8; ip = P $_ 18; linked = P $_ 25
}
})
$ended = @(Events (Query 4634 $types) __ENDS__) + @(Events (Query 4647 $null) __READ__)
$ends = @($ended | ForEach-Object { [pscustomobject]@{ t = Ms $_.TimeCreated; id = P $_ 3 } })
$first = @(Events '*' 1 -Oldest)
[pscustomobject]@{
computer = $env:COMPUTERNAME
canary = $canary
own_ip = $ownIp
winrm_peers = $peers
oldest = if ($first.Count -gt 0) { Ms $first[0].TimeCreated } else { $null }
logons = $logons
ends = $ends
} | ConvertTo-Json -Compress -Depth 4
"""
#: The script: the window, a day for its own logon, and the events read, filled in.
_PS_LOGIN_SESSIONS = (
_PS_SESSIONS_TEMPLATE.replace("__WINDOW_MS__", str(SESSION_WINDOW_DAYS * _DAY_MS))
.replace("__DAY_MS__", str(_DAY_MS))
.replace("__READ__", str(SESSIONS_READ))
.replace("__ENDS__", str(2 * SESSIONS_READ))
)
def _iso(ms: Any) -> str | None:
if not isinstance(ms, int | float) or isinstance(ms, bool):
return None
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
def _id(value: Any) -> int | None:
"""A logon ID as the event gives it, decimal; None for none or 0 (no linked logon)."""
try:
number = int(str(value))
except ValueError:
return None
return number or None
def _own_address(raw: dict[str, Any]) -> str | None:
"""Where this reading's own WinRM logon came from: its 4624 event's address, else the
one client connected to WinRM."""
own = session_address(raw.get("own_ip")) if raw.get("canary") else None
if own is not None:
return own
peers = {session_address(str(p)) for p in _as_list(raw.get("winrm_peers"))} - {None}
return peers.pop() if len(peers) == 1 else None
def _user(event: dict[str, Any], computer: str) -> str:
user, domain = str(event.get("user") or ""), str(event.get("domain") or "")
return user if not domain or domain.upper() == computer.upper() else f"{domain}\\{user}"
def _address(event: dict[str, Any], tty: str) -> str | None:
address = session_address(event.get("ip"))
if tty == "console" and address is not None:
try:
if ipaddress.ip_address(address).is_loopback:
return None
except ValueError:
return address
return address
def _ends(raw: dict[str, Any]) -> dict[int, list[int]]:
"""Each logon ID's logoffs, in milliseconds: an ID is used again after a restart."""
ends: dict[int, list[int]] = {}
for end in _as_list(raw.get("ends")):
logon, at = _id(end.get("id")), end.get("t")
if logon is not None and isinstance(at, int):
ends.setdefault(logon, []).append(at)
return ends
def _logons(events: list[dict[str, Any]]) -> Iterable[dict[str, Any]]:
"""The 4624 events of a person's interactive logon, one per linked pair."""
seen: set[int] = set()
for event in sorted(events, key=lambda e: int(e["t"])):
logon, linked = _id(event.get("id")), _id(event.get("linked"))
if logon is None or str(event.get("type")) not in LOGON_TYPES:
continue
if not str(event.get("sid") or "").upper().startswith(_PERSON_SIDS):
continue
key = min(logon, linked) if linked else logon
if key not in seen:
seen.add(key)
yield event
def _session(event: dict[str, Any], computer: str, ends: dict[int, list[int]]) -> LoginSessionDict:
tty = LOGON_TYPES[str(event.get("type"))]
started = int(event["t"])
ids = [i for i in (_id(event.get("id")), _id(event.get("linked"))) if i is not None]
ended = [at for i in ids for at in ends.get(i, ()) if at >= started]
return {
"user": _user(event, computer),
"tty": tty,
"address": _address(event, tty),
"started": _iso(started) or "",
"ended": _iso(min(ended)) if ended else None,
}
def _audited_logons(raw: dict[str, Any]) -> list[dict[str, Any]]:
"""The logon events read; raises when the log holds none, not even this reading's own."""
logons = [e for e in _as_list(raw.get("logons")) if isinstance(e, dict)]
if raw.get("canary") is False and not logons:
raise LoginSessionsUnavailable(
"the Security log holds no logon, not even this reading's own: logons are not audited"
)
return [e for e in logons if isinstance(e.get("t"), int)]
def _sessions(
logons: list[dict[str, Any]], raw: dict[str, Any], own: str | None
) -> list[LoginSessionDict]:
"""The sessions newest first, those from *own* left out, at most SESSIONS_READ."""
computer, ends = str(raw.get("computer") or ""), _ends(raw)
sessions = [_session(e, computer, ends) for e in _logons(logons)]
sessions = [s for s in sessions if own is None or s["address"] != own]
sessions.sort(key=lambda s: s["started"], reverse=True)
return sessions[:SESSIONS_READ]
def parse_login_sessions(raw: dict[str, Any]) -> LoginSessionsDict:
"""What :data:`_PS_LOGIN_SESSIONS` emitted, as napalm-device-types' reading.
:raises LoginSessionsUnavailable: when the host does not audit logons.
"""
logons = _audited_logons(raw)
own = _own_address(raw)
return {
"own_address": own,
"sessions": _sessions(logons, raw, own),
"records_since": _iso(raw.get("oldest")),
}
class WindowsLoginSessionsMixin:
"""``get_login_sessions`` for the driver, which carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_login_sessions(self) -> LoginSessionsDict:
"""The console and Remote Desktop logins of the last seven days, newest first, in
napalm-device-types' ``LoginSessionsDict``; see the module.
:raises LoginSessionsUnavailable: when the host does not audit logons.
:raises ValueError: when the reading came back empty.
"""
out = self._run_raw(_PS_LOGIN_SESSIONS).strip()
raw = json.loads(out) if out else None
if not isinstance(raw, dict):
raise ValueError("the login session reading came back empty")
return parse_login_sessions(raw)
+14
View File
@@ -0,0 +1,14 @@
"""Who can log in to a Windows host and who did, for the access review (NetOrk/netork#2895).
:class:`WindowsLoginsMixin` is both readings, :mod:`napalm_windows.login_accounts` and
:mod:`napalm_windows.login_sessions`, as one base of the driver.
"""
from __future__ import annotations
from napalm_windows.login_accounts import WindowsLoginAccountsMixin
from napalm_windows.login_sessions import WindowsLoginSessionsMixin
class WindowsLoginsMixin(WindowsLoginAccountsMixin, WindowsLoginSessionsMixin):
"""``get_login_accounts`` and ``get_login_sessions``; the driver carries the scripts."""
-143
View File
@@ -1,143 +0,0 @@
"""Local accounts on Windows as napalm-device-types' ``UserDict`` (NetOrk/netork#2889).
:class:`WindowsOsUsersMixin` gives the driver ``get_os_users``. One script reads the
accounts (``Get-LocalUser``), the local groups with their members
(``Get-LocalGroupMember``) and the profiles' paths (``Win32_UserProfile``).
Windows names an account by its security identifier, not a number:
* ``uid`` is the relative identifier, the SID's last part: 500 for the built-in
Administrator, 501 Guest, 1000 and up for accounts created. ``sid`` is the whole SID.
* ``gid`` is 513, the primary group every local account has ("None"); Windows offers
no other for them.
* ``home`` is the profile's folder, empty for an account that never logged on and so
has none; ``shell`` is empty.
* ``groups`` are the local groups the account is a direct member of. A group whose
members cannot be read -- ``Get-LocalGroupMember`` fails on a member SID it cannot
resolve, and the ADSI fallback failed too -- names nobody.
These are the host's own accounts. Who may log in and how (administrators, RDP rights,
domain accounts) is the login accounts' contract, not this one. A domain controller
has no local accounts -- ``Get-LocalUser`` would list the domain's -- and a host without
the LocalAccounts module cannot list them; both raise ``NotImplementedError``.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm_device_types.models import UserDict
from napalm_windows._powershell import _as_list
from napalm_windows._reading import json_object
logger = logging.getLogger(__name__)
_PS_OS_USERS = r"""
$ErrorActionPreference = 'Stop'
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
$local = [bool](Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue)
$users = @()
$groups = @()
if ($role -lt 4 -and $local) {
$homes = @{}
Get-CimInstance -ClassName Win32_UserProfile | ForEach-Object {
$homes[[string]$_.SID] = [string]$_.LocalPath
}
$users = @(Get-LocalUser | ForEach-Object {
$sid = [string]$_.SID
[pscustomobject]@{ name = [string]$_.Name; sid = $sid; home = $homes[$sid] }
})
$groups = @(Get-LocalGroup | ForEach-Object {
$group = $_
$members = $null
try {
$members = @(Get-LocalGroupMember -SID $group.SID | ForEach-Object { [string]$_.SID })
} catch {
try {
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME/$($group.Name),group"
$members = @($adsi.psbase.Invoke('Members') | ForEach-Object {
$bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)
(New-Object System.Security.Principal.SecurityIdentifier($bytes, 0)).Value
})
} catch { $members = $null }
}
[pscustomobject]@{ name = [string]$group.Name; members = $members }
})
}
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
domain_role = $role
local_accounts = $local
users = $users
groups = $groups
})
"""
#: ``Win32_ComputerSystem.DomainRole`` of a backup and of a primary domain controller.
_DOMAIN_CONTROLLER = 4
#: DOMAIN_GROUP_RID_USERS: the primary group of every local account.
_PRIMARY_GROUP = 513
def _rid(sid: str) -> int:
tail = sid.rsplit("-", 1)[-1]
return int(tail) if tail.isdigit() else 0
def _memberships(groups: list[Any]) -> dict[str, list[str]]:
"""SID -> the names of the groups it is a direct member of, in the order read."""
member_of: dict[str, list[str]] = {}
for group in groups:
members = group.get("members")
if members is None:
logger.warning("the members of local group %r could not be read", group.get("name"))
continue
for sid in _as_list(members):
member_of.setdefault(str(sid), []).append(str(group["name"]))
return member_of
def parse_os_users(raw: dict[str, Any]) -> list[UserDict]:
"""``_PS_OS_USERS``'s JSON as ``UserDict``s; see the module.
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
"""
if int(raw.get("domain_role") or 0) >= _DOMAIN_CONTROLLER:
raise NotImplementedError(
"a domain controller has no local accounts; its accounts are the domain's"
)
if not raw.get("local_accounts"):
raise NotImplementedError("Get-LocalUser is not available on this host")
member_of = _memberships(_as_list(raw.get("groups")))
users: list[UserDict] = []
for user in _as_list(raw.get("users")):
sid = str(user.get("sid") or "")
users.append(
{
"username": str(user["name"]),
"uid": _rid(sid),
"gid": _PRIMARY_GROUP,
"home": str(user.get("home") or ""),
"shell": "",
"groups": member_of.get(sid, []),
"sid": sid,
}
)
return users
class WindowsOsUsersMixin:
"""``get_os_users`` from the LocalAccounts cmdlets; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_os_users(self) -> list[UserDict]:
"""The host's local accounts; see the module.
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
:raises ValueError: when the reading came back empty.
"""
return parse_os_users(json_object(self._run_raw(_PS_OS_USERS), "local account"))
-119
View File
@@ -1,119 +0,0 @@
"""Installed software on Windows as packages (NetOrk/netork#2890).
:class:`WindowsPackagesMixin` gives the driver napalm-device-types' ``get_packages``
(``PackageDict``) from the machine-wide Uninstall keys, the list "Apps & features" and
``winget list`` read too:
* ``HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall``: the host's native
programs (``x64``, ``arm64`` on ARM, ``x86`` on a 32-bit Windows);
* ``HKLM\\SOFTWARE\\WOW6432Node\\...\\Uninstall``: the 32-bit programs of a 64-bit
Windows (``x86``).
A 32-bit and a 64-bit install of one program stay two packages, told apart by
``architecture``. Left out: keys without a ``DisplayName``, ``SystemComponent=1``
(parts Windows or a suite hides from the list) and entries with a ``ParentKeyName``
(updates listed under their product; Windows' own updates are the update history's).
``source`` is ``msi`` for a Windows Installer package (``WindowsInstaller=1``), else
``exe``; ``size`` is ``EstimatedSize`` (KiB) in bytes, 0 where none is given;
``publisher`` is the vendor the program names.
Not read: per-user installs (a user's own ``HKU`` hive -- over WinRM ``HKCU`` is the
connecting account's, and the hives of whoever is logged on would make the list change
with them), Store and MSIX apps, and winget, which is a per-user App Execution Alias
that does not work reliably in a WinRM session. Nothing is installed or removed.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types.models import PackageDict
from napalm_windows._powershell import _as_list
_UNINSTALL = r"Microsoft\Windows\CurrentVersion\Uninstall"
_PS_PACKAGES = rf"""
$ErrorActionPreference = 'Stop'
$native = switch ($env:PROCESSOR_ARCHITECTURE) {{
'ARM64' {{ 'arm64' }}
'x86' {{ 'x86' }}
default {{ 'x64' }}
}}
$keys = @(
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\{_UNINSTALL}'; arch = $native }},
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\WOW6432Node\{_UNINSTALL}'; arch = 'x86' }}
)
ConvertTo-Json -Compress -Depth 3 -InputObject @(
foreach ($key in $keys) {{
if (Test-Path -LiteralPath $key.path) {{
Get-ChildItem -LiteralPath $key.path -ErrorAction SilentlyContinue | ForEach-Object {{
[pscustomobject]@{{
key = [string]$_.PSChildName
arch = $key.arch
name = [string]$_.GetValue('DisplayName')
version = [string]$_.GetValue('DisplayVersion')
publisher = [string]$_.GetValue('Publisher')
system = [string]$_.GetValue('SystemComponent')
parent = [string]$_.GetValue('ParentKeyName')
msi = [string]$_.GetValue('WindowsInstaller')
size = [string]$_.GetValue('EstimatedSize')
}}
}}
}}
}}
)
"""
class WindowsPackageDict(PackageDict):
"""A program from the Uninstall keys, with whose it is and which build."""
publisher: str
architecture: str # x64, x86 or arm64
def _size(value: Any) -> int:
text = str(value or "").strip()
return int(text) * 1024 if text.isdigit() else 0
def _listed(entry: dict[str, Any]) -> bool:
"""A program the host lists as installed: named, not hidden, not an update."""
return bool(
str(entry.get("name") or "").strip()
and str(entry.get("system") or "") != "1"
and not str(entry.get("parent") or "").strip()
)
def _package(entry: dict[str, Any]) -> WindowsPackageDict:
return {
"name": str(entry["name"]).strip(),
"version": str(entry.get("version") or "").strip(),
"installed": True,
"description": "",
"size": _size(entry.get("size")),
"source": "msi" if str(entry.get("msi") or "") == "1" else "exe",
"publisher": str(entry.get("publisher") or "").strip(),
"architecture": str(entry.get("arch") or ""),
}
def parse_packages(raw: Any) -> list[PackageDict]:
"""``_PS_PACKAGES``'s JSON as packages, by name; see the module."""
packages = [_package(e) for e in _as_list(raw) if isinstance(e, dict) and _listed(e)]
packages.sort(key=lambda p: (p["name"].lower(), p["architecture"]))
return list(packages)
class WindowsPackagesMixin:
"""``get_packages`` from the Uninstall keys; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_ps(self, script: str) -> Any: ...
def get_packages(self) -> list[PackageDict]:
"""The programs installed for the whole machine; see the module."""
return parse_packages(self._run_ps(_PS_PACKAGES))
-159
View File
@@ -1,159 +0,0 @@
"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889).
:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes``
(``ProcessDict``). One script reads two sources and the join happens here:
* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time
(``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and
``VirtualSize``. Read first: it is the list.
* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a
``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM
administrator has; without one the script falls back to ``Get-Process`` and the owner
is unknown (empty).
A process is reported only when both saw it with the same start: one that exited between
the two reads is dropped rather than half-filled, and a PID reused in between is another
process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves
it out.
The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per
logical processor, so 0-100; ``memory`` the working set over the visible memory;
``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local
time. Windows has no controlling terminal and no process state of that kind: ``tty``
and ``state`` are empty. A process without a readable command line (``System``,
protected processes) shows its image name. Command lines are reported as the host
gives them, as ``ps`` does on Linux.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
from napalm_device_types.models import ProcessDict
from napalm_windows._powershell import _as_list
from napalm_windows._reading import json_object
_PS_PROCESSES = r"""
$ErrorActionPreference = 'Stop'
function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } }
function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } }
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object {
[pscustomobject]@{
pid = [int]$_.ProcessId
ppid = [int]$_.ParentProcessId
name = [string]$_.Name
command = [string]$_.CommandLine
started = Unix $_.CreationDate
offset = Offset $_.CreationDate
cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime
ws = [int64]$_.WorkingSetSize
vsz = [int64]$_.VirtualSize
}
})
try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) }
$owners = @($running | ForEach-Object {
$start = $null
try { $start = Unix $_.StartTime } catch { }
[pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start }
})
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{
now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
cores = [int]$cs.NumberOfLogicalProcessors
memory_kib = [int64]$os.TotalVisibleMemorySize
processes = $processes
owners = $owners
})
"""
#: How far the two sources' starts of one process may differ: they round differently.
_SAME_START = 2
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def _lstart(started: int | None, offset_minutes: int) -> str:
"""Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale."""
if started is None:
return ""
t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes)
return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}"
class _Host:
"""What the reading says about the host as a whole."""
def __init__(self, raw: dict[str, Any]) -> None:
self.now = int(raw.get("now") or 0)
self.cores = max(int(raw.get("cores") or 1), 1)
self.memory_kib = int(raw.get("memory_kib") or 0)
def cpu(self, cpu_100ns: int, started: int | None) -> float:
if started is None:
return 0.0
elapsed = max(self.now - started, 1)
return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1)
def memory(self, rss_kib: int) -> float:
return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0
def _started(entry: dict[str, Any]) -> int | None:
value = entry.get("started")
return int(value) if value is not None else None
def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool:
"""False when ``Get-Process`` saw another start under this PID: it was reused."""
ours, theirs = _started(entry), _started(owner)
return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START
def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict:
started = _started(entry)
rss = int(entry.get("ws") or 0) // 1024
return {
"pid": int(entry["pid"]),
"ppid": int(entry.get("ppid") or 0),
"user": str(owner.get("user") or ""),
"cpu": host.cpu(int(entry.get("cpu") or 0), started),
"memory": host.memory(rss),
"vsz": int(entry.get("vsz") or 0) // 1024,
"rss": rss,
"tty": "",
"state": "",
"started": _lstart(started, int(entry.get("offset") or 0)),
"command": str(entry.get("command") or entry.get("name") or ""),
}
def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]:
"""``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join."""
host = _Host(raw)
owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))}
processes = []
for entry in _as_list(raw.get("processes")):
owner = owners.get(int(entry["pid"]))
if not entry["pid"] or owner is None or not _same_process(entry, owner):
continue
processes.append(_process(entry, owner, host))
return sorted(processes, key=lambda p: p["pid"])
class WindowsProcessesMixin:
"""``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries
the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_processes(self) -> list[ProcessDict]:
"""A snapshot of the running processes, shaped like ``ps``; see the module.
:raises ValueError: when the reading came back empty.
"""
return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))
-85
View File
@@ -1,85 +0,0 @@
"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888).
:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the
shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which
reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes,
in one script of its own -- not folded into ``get_facts``, so a class only the identity
needs cannot fail the facts:
* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from
SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial);
* ``Win32_BaseBoard``: ``SerialNumber``, of the first board;
* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives
the date as midnight UTC; it travels as Unix time and is read as that UTC day.
Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty
(``clean_system_identity``).
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types import clean_system_identity
from napalm_device_types.system_identity import SystemIdentityDict
from napalm_windows._reading import json_object
_PS_SYSTEM_IDENTITY = r"""
$ErrorActionPreference = 'Stop'
$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct
$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1
$bios = Get-CimInstance -ClassName Win32_BIOS
[pscustomobject]@{
uuid = [string]$product.UUID
product_serial = [string]$product.IdentifyingNumber
board_serial = if ($board) { [string]$board.SerialNumber } else { $null }
bios_vendor = [string]$bios.Manufacturer
bios_version = [string]$bios.SMBIOSBIOSVersion
bios_date = if ($bios.ReleaseDate) {
([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds()
} else { $null }
} | ConvertTo-Json -Compress
"""
def _text(raw: dict[str, Any], key: str) -> str:
return str(raw.get(key) or "")
def _utc_day(value: Any) -> str:
"""Unix time as its UTC day, ``YYYY-MM-DD``; empty for none."""
if not isinstance(value, int | float) or isinstance(value, bool):
return ""
return datetime.fromtimestamp(value, UTC).date().isoformat()
def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict:
"""``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty."""
return clean_system_identity(
system_uuid=_text(raw, "uuid"),
product_serial=_text(raw, "product_serial"),
board_serial=_text(raw, "board_serial"),
bios_vendor=_text(raw, "bios_vendor"),
bios_version=_text(raw, "bios_version"),
bios_date=_utc_day(raw.get("bios_date")),
)
class WindowsSystemIdentityMixin:
"""``get_system_identity`` from the CIM classes; the driver carries the script."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_raw(self, script: str) -> str: ...
def get_system_identity(self) -> SystemIdentityDict:
"""The host's SMBIOS identity and system firmware, each value empty when unknown
or a vendor placeholder; see the module.
:raises ValueError: when the reading came back empty.
"""
return parse_system_identity(
json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity")
)
+2 -4
View File
@@ -27,7 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
from napalm_windows._powershell import _as_list, _ps_quote
from napalm_windows.host_basics import WindowsHostBasicsMixin
from napalm_windows.logins import WindowsLoginsMixin
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
from napalm_windows.time_sync import WindowsTimeSyncMixin
from napalm_windows.transport import PowerShellError, PsrpTransport
@@ -262,9 +262,7 @@ def _is_noise_route(destination: str) -> bool:
# ---------------------------------------------------------------------------
class WindowsDriver(
WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver
):
class WindowsDriver(WindowsLoginsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver):
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
``optional_args``:
+1 -1
View File
@@ -36,7 +36,7 @@ classifiers = [
]
dependencies = [
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.35.0", # TimeSyncMixin
"napalm-device-types>=4.55.0", # LoginSessionsUnavailable, session_address
"pypsrp>=0.8",
]
+5
View File
@@ -8,3 +8,8 @@ and the Python side is tested against it here.
What they cannot prove is that the scripts produce this shape on a real host
(property names, Windows PowerShell 5.1 serialisation quirks). They are to be
replaced by output recorded from a Windows Server and a Windows 11 client.
`login_accounts_server_de.json` is a German-language domain member and
`login_accounts_client.json` a Windows 11 workgroup client, `login_sessions.json` a
domain member's Security log; their account names, SIDs and addresses are made up
(documentation ranges).
-1
View File
@@ -1 +0,0 @@
{"wu_reboot_required":false,"cbs_reboot_pending":false,"wu_reboot_key":false,"file_renames":true,"update_exe":"0","computer_name":"WIN01","active_name":"WIN01","no_auto_update":"","au_options":"4","local_au_options":"","product_type":3,"installs":[1763337600,1762732800,1760659200],"au_last_install":1762732800,"legacy_last_install":"","system_drive":{"drive":"C:","size":136363114496,"free":52613349376}}
+113
View File
@@ -0,0 +1,113 @@
{
"computer": "WIN11-01",
"domain_role": 0,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Guest",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "alice",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\alice",
"last_logon": 1764543600000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 1,
"locked_out": false
},
{
"name": "bob",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": "C:\\Users\\bob",
"last_logon": 1763942400000,
"password_last_set": 1761955200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administrators",
"members": [
{
"path": "WinNT://WORKGROUP/WIN11-01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://WORKGROUP/WIN11-01/alice",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remote Desktop Users",
"members": []
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": []
},
"rdp_deny": "1",
"rdp_deny_policy": null,
"errors": []
}
+147
View File
@@ -0,0 +1,147 @@
{
"computer": "SRV01",
"domain_role": 3,
"admin": true,
"now": 1764547200000,
"users": [
{
"name": "Administrator",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"enabled": true,
"home": "C:\\Users\\Administrator",
"last_logon": 1764374400000,
"password_last_set": 1747267200000,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "Gast",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "DefaultAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-503",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": null,
"password_expires": null,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "WDAGUtilityAccount",
"sid": "S-1-5-21-1004336348-1177238915-682003330-504",
"enabled": false,
"home": null,
"last_logon": null,
"password_last_set": 1738627200000,
"password_expires": 1766275200000,
"account_expires": null,
"bad_passwords": 0,
"locked_out": false
},
{
"name": "helpdesk",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"enabled": true,
"home": "C:\\Users\\helpdesk",
"last_logon": 1754179200000,
"password_last_set": 1753315200000,
"password_expires": 1761091200000,
"account_expires": null,
"bad_passwords": 7,
"locked_out": true
},
{
"name": "svc-backup",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1002",
"enabled": true,
"home": null,
"last_logon": 1764460800000,
"password_last_set": 1763683200000,
"password_expires": null,
"account_expires": 1764115200000,
"bad_passwords": null,
"locked_out": null
}
],
"groups": [
{
"sid": "S-1-5-32-544",
"name": "Administratoren",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Administrator",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-500"
},
{
"path": "WinNT://CONTOSO/Domänen-Admins",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-512"
},
{
"path": "WinNT://CONTOSO/jdoe",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107"
},
{
"path": "WinNT://S-1-5-21-3623811015-3361044348-30300820-1290",
"class": "User",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1290"
}
]
},
{
"sid": "S-1-5-32-555",
"name": "Remotedesktopbenutzer",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/helpdesk",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001"
},
{
"path": "WinNT://CONTOSO/RDP-Operators",
"class": "Group",
"sid": "S-1-5-21-3623811015-3361044348-30300820-1301"
}
]
},
{
"sid": "S-1-5-32-546",
"name": "Gäste",
"members": [
{
"path": "WinNT://CONTOSO/SRV01/Gast",
"class": "User",
"sid": "S-1-5-21-1004336348-1177238915-682003330-501"
}
]
}
],
"rights": {
"allow": [
"*S-1-5-32-544",
"*S-1-5-32-555"
],
"deny": [
"*S-1-5-32-546"
]
},
"rdp_deny": "0",
"rdp_deny_policy": null,
"errors": []
}
+109
View File
@@ -0,0 +1,109 @@
{
"computer": "SRV01",
"canary": true,
"own_ip": "198.51.100.2",
"winrm_peers": [
"198.51.100.2"
],
"oldest": 1764288000000,
"logons": [
{
"t": 1764543600000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "900001",
"type": "10",
"ip": "198.51.100.2",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100001",
"type": "10",
"ip": "192.0.2.10",
"linked": "100002"
},
{
"t": 1764529200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "100002",
"type": "10",
"ip": "192.0.2.10",
"linked": "100001"
},
{
"t": 1764529200000,
"sid": "S-1-5-90-0-2",
"user": "DWM-2",
"domain": "Window Manager",
"id": "100003",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764529200000,
"sid": "S-1-5-96-0-2",
"user": "UMFD-2",
"domain": "Font Driver Host",
"id": "100004",
"type": "2",
"ip": "-",
"linked": "0"
},
{
"t": 1764453600000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-500",
"user": "Administrator",
"domain": "SRV01",
"id": "200001",
"type": "2",
"ip": "127.0.0.1",
"linked": "0"
},
{
"t": 1764367200000,
"sid": "S-1-5-21-3623811015-3361044348-30300820-1107",
"user": "jdoe",
"domain": "CONTOSO",
"id": "300001",
"type": "11",
"ip": "-",
"linked": "0"
},
{
"t": 1764540000000,
"sid": "S-1-5-21-1004336348-1177238915-682003330-1001",
"user": "helpdesk",
"domain": "SRV01",
"id": "400001",
"type": "10",
"ip": "2001:db8::10",
"linked": "0"
}
],
"ends": [
{
"t": 1764536400000,
"id": "100001"
},
{
"t": 1764536400005,
"id": "100002"
},
{
"t": 1764457200000,
"id": "200001"
},
{
"t": 1764187200000,
"id": "400001"
}
]
}
-1
View File
@@ -1 +0,0 @@
{"domain_role":2,"local_accounts":true,"users":[{"name":"Administrator","sid":"S-1-5-21-1004336348-1177238915-682003330-500","home":"C:\\Users\\Administrator"},{"name":"DefaultAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-503","home":null},{"name":"Guest","sid":"S-1-5-21-1004336348-1177238915-682003330-501","home":null},{"name":"WDAGUtilityAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-504","home":null},{"name":"svc-backup","sid":"S-1-5-21-1004336348-1177238915-682003330-1001","home":"C:\\Users\\svc-backup"}],"groups":[{"name":"Administrators","members":["S-1-5-21-1004336348-1177238915-682003330-500","S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-21-3623811015-3361044348-30300820-512"]},{"name":"Backup Operators","members":["S-1-5-21-1004336348-1177238915-682003330-1001"]},{"name":"Guests","members":["S-1-5-21-1004336348-1177238915-682003330-501"]},{"name":"Remote Desktop Users","members":[]},{"name":"System Managed Accounts Group","members":["S-1-5-21-1004336348-1177238915-682003330-503"]},{"name":"Users","members":["S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-4","S-1-5-11"]}]}
-1
View File
@@ -1 +0,0 @@
[{"key":"7-Zip","arch":"x64","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"5846"},{"key":"7-Zip","arch":"x86","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"4870"},{"key":"{90160000-008C-0000-1000-0000000FF1CE}","arch":"x64","name":"Office 16 Click-to-Run Extensibility Component","version":"16.0.17126.20132","publisher":"Microsoft Corporation","system":"1","parent":"","msi":"1","size":"0"},{"key":"{AC76BA86-1033-FFFF-7760-BC15014EA700}","arch":"x86","name":"Adobe Acrobat Reader DC","version":"23.008.20470","publisher":"Adobe","system":"","parent":"","msi":"1","size":"1158000"},{"key":"KB5034441","arch":"x64","name":"Security Update for Windows Server (KB5034441)","version":"","publisher":"Microsoft Corporation","system":"","parent":"Windows Server","msi":"","size":""},{"key":"Git_is1","arch":"x64","name":"Git","version":"2.43.0","publisher":"The Git Development Community","system":"","parent":"","msi":"","size":"309000"},{"key":"AddressBook","arch":"x64","name":"","version":"","publisher":"","system":"","parent":"","msi":"","size":""},{"key":"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}","arch":"x64","name":"Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130","version":"14.38.33130.0","publisher":"Microsoft Corporation","system":"","parent":"","msi":"","size":"20532"}]
-1
View File
@@ -1 +0,0 @@
{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]}
-1
View File
@@ -1 +0,0 @@
{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600}
-211
View File
@@ -1,211 +0,0 @@
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
One script reads Windows Update's own answer (``Microsoft.Update.SystemInfo``), the
registry's restart markers, the Windows Update policy and history, and the system
drive; a fake transport answers it from tests/fixtures/synthetic/host_status.json: a
member server whose policy installs updates automatically, with file renames pending
from an installer and nothing else.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types.models import HostStatusDict
from napalm_windows import WindowsDriver
from napalm_windows import host_status as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_status.json"
MONTH = 31 * 86400
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _status(**changes: Any) -> HostStatusDict:
d = WindowsDriver("win01", "admin", "secret")
reading = {**json.loads(FIXTURE.read_text()), **changes}
d._transport = FakeTransport(json.dumps(reading))
return d.get_host_status()
def test_reads_the_host_status():
assert _status() == {
"reboot_required": False,
"reboot_reason": "files wait to be replaced at the next restart "
"(PendingFileRenameOperations)",
"auto_updates": True,
"auto_updates_last_success": 1763337600,
"auto_updates_interval": MONTH,
"filesystems": [
{
"mountpoint": "C:\\",
"total": 136363114496,
"used": 136363114496 - 52613349376,
"available": 52613349376,
}
],
}
# ── restart ───────────────────────────────────────────────────────────────────
def test_pending_file_renames_alone_need_no_restart():
# Antivirus and installers set them routinely; as a trigger they would keep the flag up.
status = _status()
assert status["reboot_required"] is False
assert "PendingFileRenameOperations" in (status["reboot_reason"] or "")
def test_windows_update_saying_so_needs_a_restart():
status = _status(wu_reboot_required=True, file_renames=False)
assert status["reboot_required"] is True
assert status["reboot_reason"] == "Windows Update needs a restart to finish installing updates"
def test_component_servicing_pending_needs_a_restart():
status = _status(cbs_reboot_pending=True, file_renames=False)
assert status["reboot_required"] is True
assert status["reboot_reason"] == "component-based servicing has a restart pending"
def test_windows_updates_registry_marker_stands_in_where_its_com_object_did_not_answer():
status = _status(wu_reboot_required=None, wu_reboot_key=True, file_renames=False)
assert status["reboot_required"] is True
def test_nothing_pending_needs_no_restart_and_gives_no_reason():
status = _status(file_renames=False)
assert status["reboot_required"] is False
assert status["reboot_reason"] is None
def test_every_marker_found_is_named():
status = _status(
wu_reboot_required=True,
cbs_reboot_pending=True,
update_exe="1",
computer_name="WIN02",
)
assert status["reboot_reason"] == "; ".join(
[
"Windows Update needs a restart to finish installing updates",
"component-based servicing has a restart pending",
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
"an update waits for a restart (UpdateExeVolatile)",
"the computer takes its new name WIN02 at the next restart",
]
)
def test_a_rename_alone_needs_no_restart_for_updates():
status = _status(file_renames=False, computer_name="WIN02")
assert status["reboot_required"] is False
assert status["reboot_reason"] == "the computer takes its new name WIN02 at the next restart"
# ── automatic updates ─────────────────────────────────────────────────────────
@pytest.mark.parametrize(
("au_options", "expected"),
[("2", False), ("3", False), ("4", True), ("7", False)],
ids=["notify", "download-only", "install", "server-notify-install-and-restart"],
)
def test_the_policys_au_options(au_options, expected):
assert _status(au_options=au_options)["auto_updates"] is expected
def test_a_policy_that_turns_automatic_updates_off():
assert _status(no_auto_update="1")["auto_updates"] is False
def test_a_policy_that_leaves_it_to_the_local_administrator():
assert _status(au_options="5", local_au_options="4")["auto_updates"] is True
assert _status(au_options="5", local_au_options="3")["auto_updates"] is False
def test_a_client_without_a_policy_installs_updates_itself():
assert _status(au_options="", product_type=1)["auto_updates"] is True
def test_a_client_ignores_a_leftover_local_setting():
# Windows 10 and 11 honour only the policy; an old AUOptions left from an upgrade stays.
assert _status(au_options="", local_au_options="2", product_type=1)["auto_updates"] is True
def test_a_server_follows_its_local_setting_without_a_policy():
assert _status(au_options="", local_au_options="4")["auto_updates"] is True
assert _status(au_options="", local_au_options="3")["auto_updates"] is False
def test_a_server_without_any_setting_cannot_tell():
status = _status(au_options="", local_au_options="")
assert status["auto_updates"] is None
assert status["auto_updates_interval"] is None
def test_without_automatic_updates_there_is_no_interval():
status = _status(au_options="3")
assert status["auto_updates_interval"] is None
assert status["auto_updates_last_success"] == 1763337600
def test_the_last_success_is_the_latest_any_source_knows():
status = _status(installs=[], au_last_install=None, legacy_last_install="2025-11-20 03:12:44")
assert status["auto_updates_last_success"] == 1763608364
status = _status(installs=[1760659200], au_last_install=1762732800)
assert status["auto_updates_last_success"] == 1762732800
def test_no_installation_known_has_no_last_success():
status = _status(installs=None, au_last_install=None, legacy_last_install="")
assert status["auto_updates_last_success"] is None
def test_an_unset_com_date_is_no_installation():
# WUA's DATE zero is 1899-12-30, which travels as a negative Unix time.
status = _status(installs=[], au_last_install=-2209161600, legacy_last_install="garbage")
assert status["auto_updates_last_success"] is None
# ── the system drive ──────────────────────────────────────────────────────────
def test_an_unread_system_drive_is_no_filesystem_reading():
assert _status(system_drive=None)["filesystems"] is None
def test_one_script_reads_it_all_each_part_on_its_own():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(FIXTURE.read_text())
d.get_host_status()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_HOST_STATUS
for part in (
"Microsoft.Update.SystemInfo",
r"Component Based Servicing\RebootPending",
"PendingFileRenameOperations",
r"Policies\Microsoft\Windows\WindowsUpdate\AU",
"QueryHistory",
"Win32_LogicalDisk",
):
assert part in script
# Each COM object is asked inside its own try, so one that does not answer over
# WinRM leaves the rest of the reading standing.
assert script.count("try {") >= 4
# No update search in the poll: that is the update reading's, and slow.
assert "Search(" not in script
+388
View File
@@ -0,0 +1,388 @@
"""Who can log in to a Windows host: local accounts, administrators, Remote Desktop
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_accounts_server_de.json (a German-language domain
member: "Administratoren", "Remotedesktopbenutzer", a domain group among the
administrators, Remote Desktop on, Guests denied it) and login_accounts_client.json (a
Windows 11 workgroup client, Remote Desktop off). What a real host emits the fixtures
cannot prove -- see the README there.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import login_accounts as mod
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
MACHINE = "S-1-5-21-1004336348-1177238915-682003330"
DOMAIN = "S-1-5-21-3623811015-3361044348-30300820"
def _raw(name: str) -> dict[str, Any]:
return json.loads((FIXTURES / f"login_accounts_{name}.json").read_text())
class FakeTransport:
def __init__(self, answer: Any) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("win01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_accounts()), host
def _by_name(reading: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {a["name"]: a for a in reading["accounts"]}
class TestGermanMemberServer:
def test_the_accounts_without_the_systems_own(self):
reading, _ = _read(_raw("server_de"))
assert [a["name"] for a in reading["accounts"]] == [
"Administrator",
"Gast",
"helpdesk",
"svc-backup",
]
def test_uid_is_the_rid_and_sid_the_whole_sid(self):
admin = _by_name(_read(_raw("server_de"))[0])["Administrator"]
assert admin["uid"] == 500
assert admin["sid"] == f"{MACHINE}-500"
assert admin["home"] == "C:\\Users\\Administrator"
assert admin["shell"] == ""
def test_the_last_login_is_the_account_databases(self):
reading, _ = _read(_raw("server_de"))
admin = _by_name(reading)["Administrator"]
assert admin["last_login"] == "2025-11-29T00:00:00+00:00"
assert admin["last_login_source"] == "sam"
assert admin["last_login_from"] is None
assert admin["last_login_port"] is None
assert reading["login_sources"] == ["sam"]
assert _by_name(reading)["Gast"]["last_login"] is None
assert _by_name(reading)["Gast"]["last_login_source"] is None
def test_administrators_are_found_by_sid_not_by_name(self):
"""The group is "Administratoren" here; S-1-5-32-544 finds it all the same."""
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["administrator"] is True
assert accounts["helpdesk"]["administrator"] is False
def test_remote_desktop_by_the_right_and_its_holders(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["remote_desktop"] is True
assert accounts["helpdesk"]["remote_desktop"] is True # Remotedesktopbenutzer
assert accounts["svc-backup"]["remote_desktop"] is False # no group holds it
def test_a_denied_group_wins_over_the_right(self):
raw = _raw("server_de")
raw["groups"][2]["members"].append(
{"path": "WinNT://CONTOSO/SRV01/helpdesk", "class": "User", "sid": f"{MACHINE}-1001"}
)
assert _by_name(_read(raw)[0])["helpdesk"]["remote_desktop"] is False
def test_denying_every_local_account_denies_them_all(self):
"""``Local account`` (S-1-5-113), as Microsoft's security baseline denies it."""
raw = _raw("server_de")
raw["rights"]["deny"].append("*S-1-5-113")
accounts = _by_name(_read(raw)[0])
assert not any(a["remote_desktop"] for a in accounts.values())
def test_a_right_given_to_everyone_reaches_every_account(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("*S-1-1-0")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_a_right_given_by_name_counts(self):
raw = _raw("server_de")
raw["rights"]["allow"].append("svc-backup")
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
def test_locked_disabled_expired_or_locked_out(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Gast"]["locked"] is True # disabled
assert accounts["helpdesk"]["locked"] is True # locked out
assert accounts["svc-backup"]["locked"] is True # expired
assert accounts["Administrator"]["locked"] is False
def test_the_lock_out_not_read_is_none(self):
raw = _raw("server_de")
raw["users"][5]["account_expires"] = None
assert _by_name(_read(raw)[0])["svc-backup"]["locked"] is None
def test_password_and_account_expiry(self):
accounts = _by_name(_read(_raw("server_de"))[0])
assert accounts["Administrator"]["password"] == "set"
assert accounts["Administrator"]["password_changed"] == "2025-05-15"
assert accounts["Administrator"]["password_expires"] == "never"
assert accounts["Administrator"]["account_expires"] == "never"
assert accounts["helpdesk"]["password_expires"] == "2025-10-22"
assert accounts["svc-backup"]["account_expires"] == "2025-11-26"
assert accounts["Gast"]["password"] is None
assert accounts["Gast"]["password_expires"] is None
def test_failed_attempts_since_the_last_login(self):
reading, _ = _read(_raw("server_de"))
accounts = _by_name(reading)
assert accounts["helpdesk"]["failed_logins"] == 7
assert accounts["svc-backup"]["failed_logins"] is None
assert accounts["helpdesk"]["failed_logins_capped"] is False
assert reading["failed_logins_source"] == "sam"
def test_read_as_an_administrator(self):
assert _read(_raw("server_de"))[0]["privileged"] is True
class TestTheGroups:
def test_the_groups_that_grant_administration_or_remote_desktop(self):
groups = _read(_raw("server_de"))[0]["groups"]
assert [(g["name"], g["sid"], g["grants"]) for g in groups] == [
("Administratoren", "S-1-5-32-544", ["administrator", "remote_desktop"]),
("Remotedesktopbenutzer", "S-1-5-32-555", ["remote_desktop"]),
]
def test_a_domain_group_among_the_administrators_by_name(self):
admins = _read(_raw("server_de"))[0]["groups"][0]["members"]
assert admins == [
{
"name": "SRV01\\Administrator",
"sid": f"{MACHINE}-500",
"local": True,
"group": False,
},
{
"name": "CONTOSO\\Domänen-Admins",
"sid": f"{DOMAIN}-512",
"local": False,
"group": True,
},
{"name": "CONTOSO\\jdoe", "sid": f"{DOMAIN}-1107", "local": False, "group": False},
{"name": f"{DOMAIN}-1290", "sid": f"{DOMAIN}-1290", "local": False, "group": False},
]
def test_a_principal_of_the_host_itself_is_local(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://NT-AUTORITÄT/INTERAKTIV", "class": "Group", "sid": "S-1-5-4"}
]
member = _read(raw)[0]["groups"][1]["members"][0]
assert member == {
"name": "NT-AUTORITÄT\\INTERAKTIV",
"sid": "S-1-5-4",
"local": True,
"group": True,
}
def test_without_a_sid_the_path_tells(self):
raw = _raw("server_de")
raw["groups"][1]["members"] = [
{"path": "WinNT://CONTOSO/SRV01/old", "class": "", "sid": None},
{"path": "WinNT://CONTOSO/someone", "class": "User", "sid": None},
{"path": "", "class": "", "sid": None},
]
raw["users"] = []
members = _read(raw)[0]["groups"][1]["members"]
assert [(m["name"], m["local"], m["group"]) for m in members] == [
("SRV01\\old", True, None),
("CONTOSO\\someone", False, False),
("", None, None),
]
def test_a_domain_sid_without_the_hosts_own_is_told_by_its_path(self):
raw = _raw("server_de")
raw["users"] = []
admins = _read(raw)[0]["groups"][0]["members"]
assert [m["local"] for m in admins] == [True, False, False, None]
class TestWindows11Client:
def test_remote_desktop_off_lets_no_one_in(self):
reading, _ = _read(_raw("client"))
accounts = _by_name(reading)
assert {a["remote_desktop"] for a in accounts.values()} == {False}
assert [g["sid"] for g in reading["groups"]] == ["S-1-5-32-544"]
assert reading["groups"][0]["grants"] == ["administrator"]
def test_the_owner_is_an_administrator_the_other_user_is_not(self):
accounts = _by_name(_read(_raw("client"))[0])
assert accounts["alice"]["administrator"] is True
assert accounts["bob"]["administrator"] is False
def test_group_policy_wins_over_the_local_setting(self):
raw = _raw("client")
raw["rdp_deny_policy"] = "0"
accounts = _by_name(_read(raw)[0])
assert accounts["alice"]["remote_desktop"] is True
assert accounts["bob"]["remote_desktop"] is False
class TestNotRead:
def test_rights_not_read_leave_remote_desktop_unknown(self):
raw = _raw("server_de")
raw["rights"] = None
raw["admin"] = False
reading, _ = _read(raw)
assert {a["remote_desktop"] for a in reading["accounts"]} == {None}
assert [g["grants"] for g in reading["groups"]] == [["administrator"]]
assert reading["privileged"] is False
def test_the_remote_desktop_setting_not_read_is_unknown(self):
raw = _raw("server_de")
raw["rdp_deny"] = None
assert {a["remote_desktop"] for a in _read(raw)[0]["accounts"]} == {None}
def test_administrators_not_read_is_unknown(self, caplog):
raw = _raw("server_de")
raw["groups"] = [g for g in raw["groups"] if g["sid"] != "S-1-5-32-544"]
raw["errors"] = ["group S-1-5-32-544: Zugriff verweigert"]
with caplog.at_level("INFO"):
reading, _ = _read(raw)
assert {a["administrator"] for a in reading["accounts"]} == {None}
assert "Zugriff verweigert" in caplog.text
def test_no_failed_attempts_read_has_no_source(self):
raw = _raw("server_de")
for user in raw["users"]:
user["bad_passwords"] = None
assert _read(raw)[0]["failed_logins_source"] is None
def test_one_group_member_arrives_as_an_object(self):
"""ConvertTo-Json writes a one-element array as its element."""
raw = _raw("server_de")
raw["groups"][1]["members"] = raw["groups"][1]["members"][0]
raw["users"] = raw["users"][0]
reading, _ = _read(raw)
assert [a["name"] for a in reading["accounts"]] == ["Administrator"]
assert len(reading["groups"][1]["members"]) == 1
def test_without_get_localuser_the_reading_is_not_supported(self):
raw = _raw("server_de")
raw["users"] = None
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
_read(raw)
@pytest.mark.parametrize("answer", ["", "[]", "null"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
def test_an_account_without_a_sid_is_left_out(self):
raw = _raw("server_de")
raw["users"].append({"name": "odd", "sid": None})
raw["users"].append("garbage")
assert "odd" not in _by_name(_read(raw)[0])
class TestDomainController:
def test_its_accounts_are_the_directorys_its_groups_are_read(self):
raw = copy.deepcopy(_raw("server_de"))
raw.update(domain_role=5, users=[])
reading, _ = _read(raw)
assert reading["accounts"] == []
assert reading["login_sources"] == []
assert reading["failed_logins_source"] is None
assert reading["groups"][0]["sid"] == "S-1-5-32-544"
def test_a_domain_controller_without_get_localuser_is_read_all_the_same(self):
raw = _raw("server_de")
raw.update(domain_role=4, users=None)
assert _read(raw)[0]["accounts"] == []
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw("server_de"))
assert host.sent == [mod._PS_LOGIN_ACCOUNTS]
def test_the_conventions(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "$ErrorActionPreference = 'Stop'" in script
assert "Get-Command -Name Get-LocalUser" in script
assert "ToUnixTimeMilliseconds" in script
assert "ConvertTo-Json -Compress -Depth 6" in script
def test_groups_are_named_by_sid_never_by_their_english_name(self):
script = mod._PS_LOGIN_ACCOUNTS
assert "'S-1-5-32-544'" in script and "'S-1-5-32-555'" in script
assert "Translate([Security.Principal.NTAccount])" in script
assert "WinNT://' + $env:COMPUTERNAME + '/Administrators" not in script
def test_it_reads_no_secret_and_leaves_nothing_behind(self):
"""The only file is secedit's export of the user rights, removed in ``finally``."""
script = mod._PS_LOGIN_ACCOUNTS
assert "/areas USER_RIGHTS" in script
assert "finally { Remove-Item -LiteralPath $cfg" in script
for verb in (
"Set-LocalUser",
"Add-LocalGroupMember",
"net user",
"SetPassword",
"/configure",
):
assert verb not in script
def test_a_native_command_runs_inside_cmd_with_stderr_merged(self):
"""A line on stderr would be an error record in a remote session (time_sync.py)."""
assert "cmd.exe /c ('secedit " in mod._PS_LOGIN_ACCOUNTS
assert "' 2>&1')" in mod._PS_LOGIN_ACCOUNTS
+290
View File
@@ -0,0 +1,290 @@
"""The logins a Windows host recorded: console and Remote Desktop, from the Security log
(NetOrk/netork#2895).
The reading is one script whose JSON a fake transport answers, from
tests/fixtures/synthetic/login_sessions.json: a domain member with a Remote Desktop logon
of an administrator (two linked events), its window manager's and font driver's logons, a
local console logon, a cached one, one over IPv6 and one from the reading's own address.
What a real host emits the fixtures cannot prove -- see the README there.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_device_types import LoginSessionsUnavailable
from napalm_windows import WindowsDriver
from napalm_windows import login_sessions as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "login_sessions.json"
def _raw() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
class FakeTransport:
def __init__(self, answer: Any) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
def close(self) -> None:
self.is_open = False
def _read(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
d = WindowsDriver("srv01", "admin", "secret")
host = FakeTransport(raw)
d._transport = host # type: ignore[assignment]
return dict(d.get_login_sessions()), host
class TestTheSessions:
def test_console_and_remote_desktop_newest_first(self):
reading, _ = _read(_raw())
assert [(s["user"], s["tty"], s["address"]) for s in reading["sessions"]] == [
("helpdesk", "rdp", "2001:db8::10"),
("CONTOSO\\jdoe", "rdp", "192.0.2.10"),
("Administrator", "console", None),
("CONTOSO\\jdoe", "console", None),
]
def test_an_administrators_two_linked_logons_are_one_session(self):
rdp = _read(_raw())[0]["sessions"][1]
assert rdp == {
"user": "CONTOSO\\jdoe",
"tty": "rdp",
"address": "192.0.2.10",
"started": "2025-11-30T19:00:00+00:00",
"ended": "2025-11-30T21:00:00+00:00",
}
def test_the_window_manager_and_font_driver_are_no_one(self):
users = {s["user"] for s in _read(_raw())[0]["sessions"]}
assert not {"DWM-2", "UMFD-2"} & {u.split("\\")[-1] for u in users}
def test_the_hosts_own_accounts_go_by_name_alone(self):
users = [s["user"] for s in _read(_raw())[0]["sessions"]]
assert "Administrator" in users and "SRV01\\Administrator" not in users
def test_a_console_logon_ended_by_its_logoff(self):
console = _read(_raw())[0]["sessions"][2]
assert console["started"] == "2025-11-29T22:00:00+00:00"
assert console["ended"] == "2025-11-29T23:00:00+00:00"
def test_a_logon_still_running_has_no_end(self):
assert _read(_raw())[0]["sessions"][3]["ended"] is None
def test_a_logoff_before_the_logon_is_an_earlier_boots(self):
"""A logon ID is used again after a restart."""
assert _read(_raw())[0]["sessions"][0]["ended"] is None
def test_a_network_logon_or_an_unlock_is_not_a_session(self):
raw = _raw()
for kind in ("3", "7"):
raw["logons"].append(
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "SRV01",
"id": f"5{kind}",
"type": kind,
"ip": "192.0.2.99",
"linked": "0",
}
)
assert all(s["user"] != "x" for s in _read(raw)[0]["sessions"])
def test_an_entra_id_account_is_a_person(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-12-1-111-222-333-444",
"user": "alice@contoso.com",
"domain": "AzureAD",
"id": "77",
"type": "2",
"ip": "-",
"linked": None,
}
]
assert [s["user"] for s in _read(raw)[0]["sessions"]] == ["AzureAD\\alice@contoso.com"]
def test_an_event_without_an_id_or_a_time_is_skipped(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "",
"type": "2",
"ip": "-",
"linked": "0",
},
{
"t": None,
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "-",
"linked": "0",
},
"garbage",
]
raw["ends"] = [{"t": None, "id": "9"}, {"t": 1, "id": None}]
assert _read(raw)[0]["sessions"] == []
def test_a_remote_desktop_logon_from_the_loopback_keeps_it(self):
raw = _raw()
raw["logons"] = [
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "x",
"domain": "",
"id": "8",
"type": "10",
"ip": "127.0.0.1",
"linked": "0",
},
{
"t": raw["oldest"],
"sid": "S-1-5-21-1-2-3-1001",
"user": "y",
"domain": "",
"id": "9",
"type": "2",
"ip": "workstation-7",
"linked": "0",
},
]
sessions = {s["user"]: s["address"] for s in _read(raw)[0]["sessions"]}
assert sessions == {"x": "127.0.0.1", "y": "workstation-7"}
def test_the_cap(self, monkeypatch):
monkeypatch.setattr(mod, "SESSIONS_READ", 2)
assert len(_read(_raw())[0]["sessions"]) == 2
class TestOwnAddress:
def test_the_readings_own_winrm_logon_names_it(self):
reading, _ = _read(_raw())
assert reading["own_address"] == "198.51.100.2"
def test_its_remote_desktop_sessions_are_left_out(self):
reading, _ = _read(_raw())
assert all(s["address"] != "198.51.100.2" for s in reading["sessions"])
def test_without_an_address_on_its_logon_the_one_winrm_client(self):
raw = _raw()
raw.update(own_ip="-", winrm_peers=["::ffff:198.51.100.2"])
assert _read(raw)[0]["own_address"] == "198.51.100.2"
def test_several_winrm_clients_name_none(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers=["198.51.100.2", "198.51.100.3"])
reading, _ = _read(raw)
assert reading["own_address"] is None
assert len(reading["sessions"]) == 5
def test_one_winrm_client_arrives_as_a_string(self):
raw = _raw()
raw.update(canary=None, own_ip=None, winrm_peers="198.51.100.4")
assert _read(raw)[0]["own_address"] == "198.51.100.4"
class TestCoverage:
def test_the_oldest_event_the_log_holds(self):
assert _read(_raw())[0]["records_since"] == "2025-11-28T00:00:00+00:00"
def test_an_empty_log_has_none(self):
raw = _raw()
raw["oldest"] = None
assert _read(raw)[0]["records_since"] is None
def test_no_logon_not_even_its_own_is_no_audit(self):
raw = _raw()
raw.update(canary=False, logons=[])
with pytest.raises(LoginSessionsUnavailable, match="not audited"):
_read(raw)
def test_its_own_logon_not_found_with_others_is_read(self):
raw = _raw()
raw["canary"] = False
reading, _ = _read(raw)
assert reading["own_address"] == "198.51.100.2" # the one WinRM client
assert len(reading["sessions"]) == 4
def test_no_logon_while_its_own_was_not_looked_for_is_nobody(self):
raw = _raw()
raw.update(canary=None, logons=[])
assert _read(raw)[0]["sessions"] == []
@pytest.mark.parametrize("answer", ["", "[]"])
def test_an_empty_answer_raises(self, answer):
with pytest.raises(ValueError, match="empty"):
_read(answer)
class TestTheScript:
def test_it_is_one_round_trip(self):
_, host = _read(_raw())
assert host.sent == [mod._PS_LOGIN_SESSIONS]
def test_no_match_is_none_not_an_error(self):
assert "NoMatchingEventsFound" in mod._PS_LOGIN_SESSIONS
def test_the_window_is_bounded_on_the_host(self):
script = mod._PS_LOGIN_SESSIONS
assert "timediff(@SystemTime) <= 604800000" in script
assert "-MaxEvents $max" in script
assert "__" not in script
def test_only_console_remote_desktop_and_cached_logons(self):
script = mod._PS_LOGIN_SESSIONS
assert "$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)" in script
assert "Logon 3" not in script and "Logon 7" not in script
def test_the_conventions(self):
script = mod._PS_LOGIN_SESSIONS
assert "$ErrorActionPreference = 'Stop'" in script
assert "ToUnixTimeMilliseconds" in script
assert "Clear-EventLog" not in script and "wevtutil" not in script
-103
View File
@@ -1,103 +0,0 @@
"""Local accounts on Windows as ``UserDict`` (NetOrk/netork#2889).
One script reads ``Get-LocalUser``, ``Get-LocalGroup`` with their members and the
profiles' paths; a fake transport answers it from tests/fixtures/synthetic/os_users.json,
a member server as Windows installs it plus one account created (``svc-backup``).
Windows names an account by its SID: ``uid`` is its relative identifier, ``sid`` the
whole of it (napalm-device-types' ``UserDict.sid``).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import os_users as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "os_users.json"
BASE = "S-1-5-21-1004336348-1177238915-682003330"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _reading(**changes: Any) -> dict[str, Any]:
return {**json.loads(FIXTURE.read_text()), **changes}
def _users(reading: dict[str, Any] | None = None) -> dict[str, Any]:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
return {u["username"]: u for u in d.get_os_users()}
def test_an_account_created_reads_like_a_posix_one():
assert _users()["svc-backup"] == {
"username": "svc-backup",
"uid": 1001,
"gid": 513,
"home": "C:\\Users\\svc-backup",
"shell": "",
"groups": ["Administrators", "Backup Operators", "Users"],
"sid": f"{BASE}-1001",
}
def test_the_built_in_accounts_keep_their_well_known_rids():
users = _users()
assert users["Administrator"]["uid"] == 500
assert users["Guest"]["uid"] == 501
assert users["Guest"]["groups"] == ["Guests"]
def test_an_account_that_never_logged_on_has_no_home():
assert _users()["Guest"]["home"] == ""
def test_a_group_whose_members_could_not_be_read_names_nobody():
# Get-LocalGroupMember and the ADSI fallback both failed: the script sends null.
reading = _reading()
reading["groups"][0]["members"] = None
assert "Administrators" not in _users(reading)["svc-backup"]["groups"]
def test_a_single_account_survives_powershells_unwrapping():
reading = _reading()
reading["users"] = reading["users"][0]
reading["groups"] = reading["groups"][0]
assert _users(reading)["Administrator"]["groups"] == ["Administrators"]
@pytest.mark.parametrize("role", [4, 5])
def test_a_domain_controller_has_no_local_accounts_to_list(role):
with pytest.raises(NotImplementedError, match="domain controller"):
_users(_reading(domain_role=role, users=[], groups=[]))
def test_a_host_without_the_local_accounts_cmdlets_cannot_list_them():
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
_users(_reading(local_accounts=False, users=[], groups=[]))
def test_one_script_reads_accounts_groups_and_profiles():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps(_reading()))
d.get_os_users()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_OS_USERS
for part in ("Get-LocalUser", "Get-LocalGroupMember", "Win32_UserProfile", "DomainRole"):
assert part in script
# Probed first, so a host without the module says so instead of failing.
assert "Get-Command -Name Get-LocalUser" in script
-123
View File
@@ -1,123 +0,0 @@
"""Installed software on Windows: the machine-wide Uninstall keys (NetOrk/netork#2890).
One script reads the native and the 32-bit (``WOW6432Node``) Uninstall key of HKLM; a
fake transport answers it from tests/fixtures/synthetic/packages.json. The fixture holds
the cases the issue names: 7-Zip installed both as a 64-bit and a 32-bit program, a
``SystemComponent`` entry, and an update listed under its product (``ParentKeyName``).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import packages as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "packages.json"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _reading() -> list[dict[str, Any]]:
return json.loads(FIXTURE.read_text())
def _driver(reading: Any = None) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps(_reading() if reading is None else reading))
return d
def _packages(reading: Any = None) -> list[Any]:
return list(_driver(reading).get_packages())
def test_a_program_reads_as_a_package():
git = next(p for p in _packages() if p["name"] == "Git")
assert git == {
"name": "Git",
"version": "2.43.0",
"installed": True,
"description": "",
"size": 309000 * 1024,
"source": "exe",
"publisher": "The Git Development Community",
"architecture": "x64",
}
def test_a_windows_installer_package_is_msi():
acrobat = next(p for p in _packages() if p["name"] == "Adobe Acrobat Reader DC")
assert acrobat["source"] == "msi"
assert acrobat["architecture"] == "x86"
def test_a_32_and_a_64_bit_install_of_one_program_stay_two_packages():
zips = [p for p in _packages() if p["name"].startswith("7-Zip")]
assert sorted(p["architecture"] for p in zips) == ["x64", "x86"]
def test_system_components_updates_and_unnamed_keys_are_no_packages():
names = [p["name"] for p in _packages()]
assert "Office 16 Click-to-Run Extensibility Component" not in names
assert "Security Update for Windows Server (KB5034441)" not in names
assert "" not in names
assert len(names) == 5
def test_packages_come_sorted_by_name():
names = [p["name"] for p in _packages()]
assert names == sorted(names, key=str.lower)
def test_a_missing_size_is_zero():
reading = _reading()
reading[5]["size"] = ""
assert next(p for p in _packages(reading) if p["name"] == "Git")["size"] == 0
def test_a_single_package_survives_powershells_unwrapping():
assert [p["name"] for p in _packages(_reading()[5])] == ["Git"]
def test_a_host_with_nothing_installed_has_no_packages():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport("[]")
assert d.get_packages() == []
def test_one_script_reads_both_machine_wide_keys_and_no_users_hive():
d = _driver()
d.get_packages()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_PACKAGES
assert r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" in script
assert r"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" in script
# The connecting account's own hive says nothing about the host.
assert "HKCU" not in script
assert "winget" not in script
def test_installing_and_removing_stay_not_offered():
assert not hasattr(WindowsDriver, "install_package")
assert not hasattr(WindowsDriver, "uninstall_package")
@pytest.mark.parametrize("answer", ["", "null"])
def test_an_empty_answer_has_no_packages(answer):
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(answer)
assert d.get_packages() == []
-125
View File
@@ -1,125 +0,0 @@
"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889).
One script reads both; a fake transport answers it from
tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command
line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the
owner. The fixture holds the cases the join decides:
* 0, the System Idle Process: no process, left out as ``ps`` leaves it out;
* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled;
* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID
that was reused between the two reads, dropped;
* 7777, started after ``Win32_Process`` was read: not part of the reading.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import processes as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _reading() -> dict[str, Any]:
return json.loads(FIXTURE.read_text())
def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
return d
def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]:
return {p["pid"]: p for p in _driver(reading).get_processes()}
def test_the_join_keeps_the_processes_both_reads_saw():
assert sorted(_by_pid()) == [4, 812, 4312]
def test_a_process_reads_like_ps():
assert _by_pid()[4312] == {
"pid": 4312,
"ppid": 3988,
"user": "WIN01\\admin",
# 120 CPU seconds in 600 s on 4 logical processors
"cpu": 5.0,
# 100 MiB of 8 GiB
"memory": 1.2,
"vsz": 2203500000000 // 1024,
"rss": 102400,
"tty": "",
"state": "",
# 11:50 UTC, an hour east of it
"started": "Mon Dec 1 12:50:00 2025",
"command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo',
}
def test_a_process_without_a_command_line_shows_its_name():
system = _by_pid()[4]
assert system["command"] == "System"
assert system["started"] == ""
assert system["cpu"] == 0.0
def test_a_start_one_second_apart_is_the_same_process():
# Get-Process and CIM round the start differently.
reading = _reading()
reading["owners"][2]["started"] += 1
assert 812 in _by_pid(reading)
def test_without_elevation_the_owner_is_unknown():
# Get-Process -IncludeUserName needs an elevated session; the script falls back.
reading = _reading()
for owner in reading["owners"]:
owner.pop("user")
assert {p["user"] for p in _by_pid(reading).values()} == {""}
def test_cpu_stays_within_a_hundred_percent():
reading = _reading()
reading["processes"][3]["cpu"] = 10**13
assert _by_pid(reading)[4312]["cpu"] == 100.0
def test_a_single_process_survives_powershells_unwrapping():
reading = _reading()
reading["processes"] = reading["processes"][2]
reading["owners"] = reading["owners"][2]
assert sorted(_by_pid(reading)) == [812]
def test_one_script_reads_both_sources():
d = _driver()
d.get_processes()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_PROCESSES
assert "Win32_Process" in script
assert "Get-Process -IncludeUserName" in script
def test_an_empty_answer_is_no_reading():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport("")
with pytest.raises(ValueError):
d.get_processes()
-93
View File
@@ -1,93 +0,0 @@
"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888).
One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``;
a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell
server as the classes describe it. The placeholders are napalm-device-types' own
(``clean_system_identity``).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from napalm_windows import WindowsDriver
from napalm_windows import system_identity as mod
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json"
class FakeTransport:
def __init__(self, answer: str) -> None:
self.answer = answer
self.sent: list[str] = []
self.is_open = True
def run(self, script: str) -> str:
self.sent.append(script)
return self.answer
def _driver(**changes: Any) -> WindowsDriver:
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes}))
return d
def test_reads_the_identity_and_the_firmware():
assert _driver().get_system_identity() == {
"system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732",
"product_serial": "4B5QM72",
"board_serial": ".4B5QM72.CNCMS0012345AB.",
"bios_vendor": "Dell Inc.",
"bios_version": "2.19.0",
"bios_date": "2023-08-15",
}
def test_one_script_reads_the_three_classes():
d = _driver()
d.get_system_identity()
(script,) = d._transport.sent # type: ignore[union-attr]
assert script == mod._PS_SYSTEM_IDENTITY
for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"):
assert cls in script
@pytest.mark.parametrize(
("field", "value"),
[
("product_serial", "To be filled by O.E.M."),
("board_serial", "Default string"),
("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"),
("uuid", "03000200-0400-0500-0006-000700080009"),
("bios_vendor", "To be filled by O.E.M."),
],
)
def test_oem_placeholders_read_as_empty(field, value):
identity = _driver(**{field: value}).get_system_identity()
key = {"uuid": "system_uuid"}.get(field, field)
assert identity[key] == "" # type: ignore[literal-required]
@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"])
def test_a_value_the_host_did_not_give_reads_as_empty(field):
# A VM without a base board, a firmware without a release date: null in the JSON.
identity = _driver(**{field: None}).get_system_identity()
key = {"uuid": "system_uuid"}.get(field, field)
assert identity[key] == "" # type: ignore[literal-required]
def test_the_release_date_is_the_utc_day():
# CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time.
assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15"
def test_an_empty_answer_is_no_reading():
d = WindowsDriver("win01", "admin", "secret")
d._transport = FakeTransport("")
with pytest.raises(ValueError):
d.get_system_identity()
+5 -16
View File
@@ -5,7 +5,8 @@
Asks for the password, runs every getter script over one WinRM connection and
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
MAC and IP addresses and host names before copying anything into tests/.
MAC and IP addresses, host names, account names and SIDs before copying anything into
tests/.
"""
from __future__ import annotations
@@ -14,16 +15,7 @@ import argparse
import getpass
import pathlib
from napalm_windows import (
WindowsDriver,
host_status,
os_users,
packages,
processes,
scheduled_tasks,
system_identity,
time_sync,
)
from napalm_windows import WindowsDriver, login_accounts, login_sessions, scheduled_tasks, time_sync
from napalm_windows import windows as mod
SCRIPTS = {
@@ -36,11 +28,8 @@ SCRIPTS = {
"listening": mod._PS_LISTENING,
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
"time_sync": time_sync._PS_TIME_SYNC,
"system_identity": system_identity._PS_SYSTEM_IDENTITY,
"processes": processes._PS_PROCESSES,
"os_users": os_users._PS_OS_USERS,
"packages": packages._PS_PACKAGES,
"host_status": host_status._PS_HOST_STATUS,
"login_accounts": login_accounts._PS_LOGIN_ACCOUNTS,
"login_sessions": login_sessions._PS_LOGIN_SESSIONS,
}
OUT = pathlib.Path(__file__).parent / "harvest-out"