Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0df672fb7c | ||
|
|
0bbeebb7a7 |
No files matched your search
+10
-16
@@ -7,22 +7,16 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- 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.
|
||||
- Repair runs (NetOrk/netork#2899), napalm-device-types' `HostRepairMixin`: checking the
|
||||
system files (`sfc /verifyonly`) and the component store (`DISM /ScanHealth`), updating
|
||||
Microsoft Defender's signatures and running a quick or full Defender scan. Each streams
|
||||
the tool's output line by line as the host prints it and ends with the tool's exit
|
||||
code; a failure names the tool's last lines. Each run has its own bound in time,
|
||||
which a caller's `limit` can tighten. A host without Defender says so instead of
|
||||
failing with an error. Repairing the system files or the component store is not offered
|
||||
yet: both wait for a test on a real host. `PsrpTransport.run_streaming(script,
|
||||
on_output, limit=...)` runs a long script, passing each output line on as it arrives and
|
||||
stopping it past its limit.
|
||||
- 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
|
||||
|
||||
@@ -43,8 +43,7 @@ handshake once.
|
||||
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
|
||||
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
|
||||
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
|
||||
| `get_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* |
|
||||
| `verify_system_files`, `check_component_store`, `update_antimalware_signatures`, `scan_antimalware` | `sfc /verifyonly`, `DISM /Online /Cleanup-Image /ScanHealth /English`, `Update-MpSignature`, `Start-MpScan`; streamed runs, see *Repair runs* |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
|
||||
@@ -99,40 +98,39 @@ 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.
|
||||
|
||||
### Logins
|
||||
|
||||
napalm-device-types' login readings, for the access review (NetOrk/netork#2895). Both
|
||||
are read-only, one script each, and take an administrator.
|
||||
|
||||
* **Accounts** are the host's own (`Get-LocalUser`; without it, not supported), not the
|
||||
system's `DefaultAccount` and `WDAGUtilityAccount`. `uid` is the RID, `sid` the SID;
|
||||
`shell` is empty, `home` the profile folder. The last login and the failed attempts
|
||||
since it (`BadPasswordAttempts`) are the account database's, source `sam`; an account
|
||||
is `locked` when disabled, expired or locked out. A domain controller's accounts are
|
||||
the directory's and are not read.
|
||||
* **Administrators and Remote Desktop** go by SID, so a German host's "Administratoren"
|
||||
is found: `administrator` is membership of `S-1-5-32-544`; `remote_desktop` that the
|
||||
host takes Remote Desktop logins (`fDenyTSConnections`, group policy first) and the
|
||||
account holds `SeRemoteInteractiveLogonRight` without being denied it, through
|
||||
itself, a local group, or a SID every local logon carries (Everyone, Local account).
|
||||
`groups` lists the groups that grant either, with every member as the host names it,
|
||||
a domain's groups included. secedit's export goes to a file under
|
||||
`%SystemRoot%\Temp`, removed at once.
|
||||
* **Sessions** are logon events 4624 of type 2 (console), 10 (Remote Desktop) and 11
|
||||
(cached, at the console) of the last seven days, the newest 1000, as `tty` `console`
|
||||
or `rdp`; network logons (type 3) are not, since every WinRM and SMB connection is
|
||||
one. A person's account only: not `DWM-n` or `UMFD-n`. An administrator's two linked
|
||||
logons are one session; the end is its logoff (4634, 4647). `own_address` is the
|
||||
address of the reading's own WinRM logon, found by its logon ID, else the one client
|
||||
connected to WinRM; its sessions are left out. `records_since` is the Security log's
|
||||
oldest event: the log rotates by size, so a login before it is unknown. A log that
|
||||
holds no logon, not even the reading's own, raises `LoginSessionsUnavailable`.
|
||||
* **Not read:** OpenSSH for Windows logins and the Remote Desktop session manager's own
|
||||
log (`TerminalServices-LocalSessionManager`); the domain's accounts.
|
||||
|
||||
Not yet: packages, Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
### Repair runs
|
||||
|
||||
napalm-device-types' `HostRepairMixin` (NetOrk/netork#2899): a fixed catalog of runs, one
|
||||
method each, so an application can start these and nothing else.
|
||||
|
||||
| Run | Tool | Bound (a caller's `limit` can tighten it) |
|
||||
|---|---|---|
|
||||
| `verify_system_files` | `sfc /verifyonly` (changes nothing) | 1 h |
|
||||
| `check_component_store` | `DISM /Online /Cleanup-Image /ScanHealth /English` (changes nothing) | 1 h |
|
||||
| `update_antimalware_signatures` | `Update-MpSignature`, with the signature version before and after | 15 min |
|
||||
| `scan_antimalware(quick=True)` | `Start-MpScan -ScanType QuickScan` (`FullScan` with `quick=False`), with what it detected | 1 h (4 h) |
|
||||
|
||||
* **Not offered yet:** `repair_system_files` (`sfc /scannow`), which may fail to start the
|
||||
repair service (TrustedInstaller) in a remote session, and `repair_component_store`
|
||||
(`DISM /RestoreHealth`), which needs a repair source WSUS-managed hosts often lack
|
||||
(`0x800f081f`). Both wait for a test on a real host.
|
||||
* **Transport:** one bounded PSRP call per run (`PsrpTransport.run_streaming`): each line
|
||||
reaches the caller's `log` as the host prints it, and a run past its limit is stopped.
|
||||
The tools run as the connection's administrator; the SYSTEM scheduled task is where a
|
||||
tool would move should a real host show it needs SYSTEM.
|
||||
* **Output:** `sfc` writes UTF-16 to a redirected stdout and is read as such; DISM runs
|
||||
with `/English` in the OEM code page. Text that still arrives as UTF-16 read byte by byte
|
||||
loses its NULs. The exit code decides: 0 succeeds, any other fails with the tool's last
|
||||
lines (an HRESULT in hex). A check that finds damage can still end with 0: the verdict is
|
||||
in its output, `sfc`'s in the host's language.
|
||||
* **Defender** runs only where `Get-Command` finds its cmdlets; elsewhere (another
|
||||
antivirus, a Server without the feature) the run fails with "not available on this
|
||||
host". A scan's detections are handled as Defender is set to handle them.
|
||||
* None of them restarts the host or creates a restore point.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
WinRM is on by default on Windows Server; on Windows 10/11 run
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
"""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)
|
||||
@@ -1,265 +0,0 @@
|
||||
"""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)
|
||||
@@ -1,14 +0,0 @@
|
||||
"""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."""
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Repair runs on Windows: SFC, DISM and Microsoft Defender (NetOrk/netork#2899).
|
||||
|
||||
:class:`WindowsRepairsMixin` implements the runs of napalm-device-types'
|
||||
:class:`~napalm_device_types.host_repairs.HostRepairMixin` this driver can do:
|
||||
|
||||
================================== ===============================================
|
||||
``verify_system_files`` ``sfc /verifyonly``
|
||||
``check_component_store`` ``DISM /Online /Cleanup-Image /ScanHealth``
|
||||
``update_antimalware_signatures`` ``Update-MpSignature``
|
||||
``scan_antimalware`` ``Start-MpScan -ScanType QuickScan|FullScan``
|
||||
================================== ===============================================
|
||||
|
||||
The two repairs, ``sfc /scannow`` and ``DISM /RestoreHealth``, are not defined, so the
|
||||
driver does not offer them: in a remote session ``sfc /scannow`` may fail to start the
|
||||
repair service (TrustedInstaller), and ``RestoreHealth`` needs a repair source that
|
||||
WSUS-managed hosts often lack. Both wait for a test on a real host.
|
||||
|
||||
**One bounded PSRP call per run.** Each run is one script streamed over the open
|
||||
connection (``PsrpTransport.run_streaming``): its lines reach ``log`` as the host
|
||||
prints them, and a run still going after its limit is stopped. The tools run as the
|
||||
connection's administrator, not through a SYSTEM scheduled task; should a real host
|
||||
show that a tool needs SYSTEM, the task building block of
|
||||
:mod:`napalm_windows.scheduled_tasks` is where it would move.
|
||||
|
||||
**Native tools** start as a process whose output is read line by line in the encoding
|
||||
the tool writes: ``sfc`` writes UTF-16 to a redirected stdout, read as such; DISM
|
||||
writes the OEM code page and runs with ``/English``, so its words are the same on
|
||||
every host. Should text still arrive as UTF-16 read byte by byte, :func:`tool_lines`
|
||||
drops the NULs between the characters. A tool missing from the host says
|
||||
``napalm-not-available:<tool>``; every script ends with ``napalm-exit-code:<n>``.
|
||||
Neither line reaches ``log``. The exit code decides (``tool_outcome``): 0 succeeds, any
|
||||
other fails with the tool's last lines. A check that finds damage may still end with 0;
|
||||
the verdict is in its output.
|
||||
|
||||
**Defender** runs only where ``Get-Command`` finds its cmdlets, so a host with another
|
||||
antivirus (or Server without the feature) fails with "not available", not an error.
|
||||
The signature update names the version before and after; a scan names what it
|
||||
detected since it started, handled as Defender is set to handle it.
|
||||
|
||||
Nothing here restarts the host or creates a restore point.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
from napalm_device_types import HostRepairMixin, HostRepairResultDict, tool_outcome
|
||||
from napalm_device_types.host_repairs import LineLog
|
||||
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_windows.transport import PsrpTransport
|
||||
|
||||
#: The longest each run may take, in seconds; a caller's ``limit`` can only tighten it.
|
||||
SFC_LIMIT = 3600
|
||||
DISM_LIMIT = 3600
|
||||
SIGNATURE_LIMIT = 900
|
||||
QUICK_SCAN_LIMIT = 3600
|
||||
FULL_SCAN_LIMIT = 4 * 3600
|
||||
|
||||
_EXIT = "napalm-exit-code:"
|
||||
_MISSING = "napalm-not-available:"
|
||||
_LINE_BREAKS = re.compile(r"\r\n|\r|\n")
|
||||
|
||||
# A native tool as a process, its stdout read line by line in the tool's encoding and
|
||||
# written to the pipeline as it comes, its stderr after it. No console is involved, so
|
||||
# nothing depends on the remote session's console code page.
|
||||
_PS_NATIVE = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Invoke-NativeTool([string]$Path, [string]$Arguments, [System.Text.Encoding]$Encoding) {
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
||||
'napalm-not-available:' + (Split-Path -Leaf $Path)
|
||||
return
|
||||
}
|
||||
$info = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$info.FileName = $Path
|
||||
$info.Arguments = $Arguments
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
$info.RedirectStandardOutput = $true
|
||||
$info.RedirectStandardError = $true
|
||||
$info.StandardOutputEncoding = $Encoding
|
||||
$info.StandardErrorEncoding = $Encoding
|
||||
$process = [System.Diagnostics.Process]::Start($info)
|
||||
$errors = $process.StandardError.ReadToEndAsync()
|
||||
while ($null -ne ($line = $process.StandardOutput.ReadLine())) { $line }
|
||||
$process.WaitForExit()
|
||||
$errors.Result -split "`r?`n" | Where-Object { $_ }
|
||||
'napalm-exit-code:' + $process.ExitCode
|
||||
}
|
||||
"""
|
||||
|
||||
_PS_SFC_VERIFY = (
|
||||
_PS_NATIVE
|
||||
+ r"""
|
||||
$sfc = Join-Path $env:SystemRoot 'System32\sfc.exe'
|
||||
Invoke-NativeTool $sfc '/verifyonly' ([System.Text.Encoding]::Unicode)
|
||||
"""
|
||||
)
|
||||
|
||||
_PS_DISM_SCAN = (
|
||||
_PS_NATIVE
|
||||
+ r"""
|
||||
$page = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage
|
||||
$dism = Join-Path $env:SystemRoot 'System32\Dism.exe'
|
||||
$arguments = '/Online /Cleanup-Image /ScanHealth /English'
|
||||
Invoke-NativeTool $dism $arguments ([System.Text.Encoding]::GetEncoding($page))
|
||||
"""
|
||||
)
|
||||
|
||||
_PS_SIGNATURE_UPDATE = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Get-Command -Name Update-MpSignature -ErrorAction SilentlyContinue)) {
|
||||
'napalm-not-available:Microsoft Defender Antivirus'
|
||||
return
|
||||
}
|
||||
function Get-SignatureLine([string]$When) {
|
||||
try {
|
||||
$status = Get-MpComputerStatus
|
||||
$at = ([datetime]$status.AntivirusSignatureLastUpdated).ToUniversalTime()
|
||||
$at = $at.ToString('yyyy-MM-dd HH:mm')
|
||||
$When + ': ' + [string]$status.AntivirusSignatureVersion + ', updated ' + $at + ' UTC'
|
||||
} catch {
|
||||
$When + ': not readable (' + $_.Exception.Message + ')'
|
||||
}
|
||||
}
|
||||
Get-SignatureLine 'Signatures before'
|
||||
$code = 0
|
||||
try { Update-MpSignature } catch { 'Update-MpSignature failed: ' + $_.Exception.Message; $code = 1 }
|
||||
Get-SignatureLine 'Signatures after'
|
||||
'napalm-exit-code:' + $code
|
||||
"""
|
||||
|
||||
# Start-MpScan returns when the scan ended. What it detected since it started is read
|
||||
# from Defender's detections, by threat name and whether Defender's action went through.
|
||||
_PS_SCAN = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Get-Command -Name Start-MpScan -ErrorAction SilentlyContinue)) {
|
||||
'napalm-not-available:Microsoft Defender Antivirus'
|
||||
return
|
||||
}
|
||||
$start = Get-Date
|
||||
'Scan started: {scan_type}'
|
||||
$code = 0
|
||||
try {
|
||||
Start-MpScan -ScanType {scan_type}
|
||||
} catch {
|
||||
'Start-MpScan failed: ' + $_.Exception.Message
|
||||
$code = 1
|
||||
}
|
||||
'Scan ended.'
|
||||
$found = @()
|
||||
try {
|
||||
$found = @(Get-MpThreatDetection | Where-Object { $_.InitialDetectionTime -ge $start })
|
||||
} catch { }
|
||||
'Threats detected: ' + $found.Count
|
||||
foreach ($detection in $found) {
|
||||
$name = [string]$detection.ThreatID
|
||||
try { $name = [string](Get-MpThreat -ThreatID $detection.ThreatID).ThreatName } catch { }
|
||||
$action = if ($detection.ActionSuccess) { 'succeeded' } else { 'not completed' }
|
||||
' ' + $name + ': action ' + $action
|
||||
}
|
||||
'napalm-exit-code:' + $code
|
||||
"""
|
||||
_PS_QUICK_SCAN = _PS_SCAN.replace("{scan_type}", "QuickScan")
|
||||
_PS_FULL_SCAN = _PS_SCAN.replace("{scan_type}", "FullScan")
|
||||
|
||||
|
||||
def tool_lines(item: str) -> list[str]:
|
||||
"""One output object of a run as lines: without NULs (UTF-16 read byte by byte) or a
|
||||
byte order mark, split at every line break -- progress ends its lines with a bare
|
||||
carriage return -- trailing spaces and blank lines dropped."""
|
||||
text = item.replace("\x00", "").replace("", "")
|
||||
return [line.rstrip() for line in _LINE_BREAKS.split(text) if line.strip()]
|
||||
|
||||
|
||||
def _exit_code(text: str) -> int | None:
|
||||
try:
|
||||
return int(text.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class _ToolRun:
|
||||
"""What a run's script printed, its exit code and a missing tool, as it arrives."""
|
||||
|
||||
def __init__(self, log: LineLog | None) -> None:
|
||||
self.log = log
|
||||
self.lines: list[str] = []
|
||||
self.exit_code: int | None = None
|
||||
self.missing: str | None = None
|
||||
|
||||
def take(self, item: str) -> None:
|
||||
for line in tool_lines(item):
|
||||
if line.startswith(_EXIT):
|
||||
self.exit_code = _exit_code(line.removeprefix(_EXIT))
|
||||
elif line.startswith(_MISSING):
|
||||
self.missing = line.removeprefix(_MISSING).strip()
|
||||
else:
|
||||
self.lines.append(line)
|
||||
if self.log is not None:
|
||||
self.log(line)
|
||||
|
||||
def outcome(self, tool: str) -> HostRepairResultDict:
|
||||
if self.missing is not None:
|
||||
return {
|
||||
"success": False,
|
||||
"output": "\n".join(self.lines),
|
||||
"exit_code": None,
|
||||
"error": f"{self.missing} is not available on this host",
|
||||
}
|
||||
return tool_outcome(self.lines, self.exit_code, tool=tool)
|
||||
|
||||
def cut_off(self, tool: str, why: str) -> HostRepairResultDict:
|
||||
return tool_outcome([*self.lines, why], None, tool=tool)
|
||||
|
||||
|
||||
class WindowsRepairsMixin(HostRepairMixin):
|
||||
"""SFC, DISM and Defender runs for :class:`~napalm_windows.windows.WindowsDriver`."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
_transport: PsrpTransport | None
|
||||
|
||||
def verify_system_files(
|
||||
self, *, log: LineLog | None = None, limit: float | None = None
|
||||
) -> HostRepairResultDict:
|
||||
"""``sfc /verifyonly``: checks the protected system files and changes nothing."""
|
||||
return self._tool_run(_PS_SFC_VERIFY, "sfc /verifyonly", SFC_LIMIT, log, limit)
|
||||
|
||||
def check_component_store(
|
||||
self, *, log: LineLog | None = None, limit: float | None = None
|
||||
) -> HostRepairResultDict:
|
||||
"""``DISM /Online /Cleanup-Image /ScanHealth``: scans the component store and
|
||||
changes nothing; up to half an hour."""
|
||||
return self._tool_run(_PS_DISM_SCAN, "DISM /ScanHealth", DISM_LIMIT, log, limit)
|
||||
|
||||
def update_antimalware_signatures(
|
||||
self, *, log: LineLog | None = None, limit: float | None = None
|
||||
) -> HostRepairResultDict:
|
||||
"""``Update-MpSignature``, with the signature version before and after."""
|
||||
return self._tool_run(
|
||||
_PS_SIGNATURE_UPDATE, "Update-MpSignature", SIGNATURE_LIMIT, log, limit
|
||||
)
|
||||
|
||||
def scan_antimalware(
|
||||
self, quick: bool = True, *, log: LineLog | None = None, limit: float | None = None
|
||||
) -> HostRepairResultDict:
|
||||
"""``Start-MpScan``, quick or full, with what it detected."""
|
||||
if quick:
|
||||
return self._tool_run(_PS_QUICK_SCAN, "Start-MpScan", QUICK_SCAN_LIMIT, log, limit)
|
||||
return self._tool_run(_PS_FULL_SCAN, "Start-MpScan", FULL_SCAN_LIMIT, log, limit)
|
||||
|
||||
def _tool_run(
|
||||
self, script: str, tool: str, bound: float, log: LineLog | None, limit: float | None
|
||||
) -> HostRepairResultDict:
|
||||
"""Run *script*; within *bound*, or the caller's *limit* where that is tighter."""
|
||||
limit = bound if limit is None else min(limit, bound)
|
||||
if self._transport is None:
|
||||
raise ConnectionClosedException("WinRM connection is not open")
|
||||
run = _ToolRun(log)
|
||||
try:
|
||||
self._transport.run_streaming(script, run.take, limit=limit)
|
||||
except (TimeoutError, PowerShellError) as exc:
|
||||
return run.cut_off(tool, str(exc))
|
||||
return run.outcome(tool)
|
||||
@@ -10,15 +10,22 @@ transport (Windows OpenSSH) would implement later.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
|
||||
from pypsrp.complex_objects import PSInvocationState
|
||||
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
|
||||
from pypsrp.powershell import PowerShell, RunspacePool
|
||||
from pypsrp.wsman import WSMan
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The longest one poll of a streaming script waits for output, so its limit is
|
||||
#: checked at least this often.
|
||||
_POLL_SECONDS = 20
|
||||
|
||||
|
||||
class PowerShellError(Exception):
|
||||
"""A script ran but wrote to PowerShell's error stream."""
|
||||
@@ -104,6 +111,49 @@ class PsrpTransport:
|
||||
raise PowerShellError(message or "PowerShell reported an error")
|
||||
return "\n".join(str(o) for o in output if o is not None)
|
||||
|
||||
def run_streaming(
|
||||
self, script: str, on_output: Callable[[str], None], *, limit: float
|
||||
) -> list[str]:
|
||||
"""Run a long script, handing each output object to *on_output* as it arrives.
|
||||
|
||||
For a run that takes minutes: the pipeline is started and polled, each poll
|
||||
waiting at most ``_POLL_SECONDS`` (and less than a read of the connection), so
|
||||
output reaches the caller while the host still works. A script still running
|
||||
after *limit* seconds is stopped (Ctrl+C to the pipeline) and raises
|
||||
:class:`TimeoutError`. An error the script wrote raises :class:`PowerShellError`
|
||||
once it ended, after its output was passed on.
|
||||
|
||||
:returns: Every output object, as text, in order.
|
||||
"""
|
||||
if self._pool is None:
|
||||
raise ConnectionClosedException("WinRM connection is not open")
|
||||
ps = PowerShell(self._pool)
|
||||
ps.add_script(script)
|
||||
poll = min(_POLL_SECONDS, max(self.timeout // 2, 1))
|
||||
deadline = time.monotonic() + limit
|
||||
taken, out = 0, []
|
||||
ps.begin_invoke()
|
||||
while ps.state == PSInvocationState.RUNNING:
|
||||
if time.monotonic() > deadline:
|
||||
self._stop(ps)
|
||||
raise TimeoutError(f"The script did not end within {int(limit)} seconds")
|
||||
ps.poll_invoke(timeout=poll)
|
||||
arrived, taken = ps.output[taken:], len(ps.output)
|
||||
for item in arrived:
|
||||
if item is not None:
|
||||
out.append(str(item))
|
||||
on_output(out[-1])
|
||||
if ps.had_errors:
|
||||
message = "; ".join(str(e) for e in ps.streams.error).strip()
|
||||
raise PowerShellError(message or "PowerShell reported an error")
|
||||
return out
|
||||
|
||||
def _stop(self, ps: PowerShell) -> None:
|
||||
try:
|
||||
ps.stop()
|
||||
except Exception: # a pipeline that ended meanwhile has nothing to stop
|
||||
logger.debug("Stopping a pipeline on %s failed", self.host, exc_info=True)
|
||||
|
||||
def run_last(self, script: str) -> bool:
|
||||
"""Run a script after which the host may stop answering: a restart, a shutdown.
|
||||
|
||||
|
||||
@@ -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.logins import WindowsLoginsMixin
|
||||
from napalm_windows.repairs import WindowsRepairsMixin
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
@@ -262,7 +262,7 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(WindowsLoginsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver):
|
||||
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsRepairsMixin, OSDriver):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.55.0", # LoginSessionsUnavailable, session_address
|
||||
"napalm-device-types>=4.35.0", # TimeSyncMixin
|
||||
"pypsrp>=0.8",
|
||||
]
|
||||
|
||||
|
||||
Vendored
+3
-4
@@ -9,7 +9,6 @@ What they cannot prove is that the scripts produce this shape on a real host
|
||||
(property names, Windows PowerShell 5.1 serialisation quirks). They are to be
|
||||
replaced by output recorded from a Windows Server and a Windows 11 client.
|
||||
|
||||
`login_accounts_server_de.json` is a German-language domain member and
|
||||
`login_accounts_client.json` a Windows 11 workgroup client, `login_sessions.json` a
|
||||
domain member's Security log; their account names, SIDs and addresses are made up
|
||||
(documentation ranges).
|
||||
The repair runs' fixtures (`*.txt`) are what their scripts stream: one output object
|
||||
per line, ending in `napalm-exit-code:<n>`. They follow Microsoft's documented output of
|
||||
`sfc`, `DISM` and the Defender cmdlets; `tools/harvest.py --runs` records the real ones.
|
||||
@@ -0,0 +1,5 @@
|
||||
Scan started: QuickScan
|
||||
Scan ended.
|
||||
Threats detected: 1
|
||||
Virus:DOS/EICAR_Test_File: action succeeded
|
||||
napalm-exit-code:0
|
||||
@@ -0,0 +1,3 @@
|
||||
Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC
|
||||
Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC
|
||||
napalm-exit-code:0
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
|
||||
Deployment Image Servicing and Management tool
|
||||
Version: 10.0.20348.681
|
||||
|
||||
Image Version: 10.0.20348.2340
|
||||
|
||||
[===== 10.0% ]
|
||||
[==========================100.0%==========================] No component store corruption detected.
|
||||
The operation completed successfully.
|
||||
napalm-exit-code:0
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
Deployment Image Servicing and Management tool
|
||||
Version: 10.0.20348.681
|
||||
|
||||
Image Version: 10.0.20348.2340
|
||||
|
||||
|
||||
Error: 0x800f081f
|
||||
|
||||
The source files could not be found.
|
||||
Use the "Source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see https://go.microsoft.com/fwlink/?LinkId=243077.
|
||||
|
||||
The DISM log file can be found at C:\Windows\Logs\DISM\dism.log
|
||||
napalm-exit-code:-2146498529
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
{
|
||||
"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
@@ -1,109 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
|
||||
Beginning system scan. This process will take some time.
|
||||
|
||||
Beginning verification phase of system scan.
|
||||
Verification 1% complete.
|
||||
Verification 52% complete.
|
||||
Verification 100% complete.
|
||||
|
||||
Windows Resource Protection did not find any integrity violations.
|
||||
napalm-exit-code:0
|
||||
@@ -1,388 +0,0 @@
|
||||
"""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
|
||||
@@ -1,290 +0,0 @@
|
||||
"""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
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Repair runs on Windows: SFC, DISM and Microsoft Defender over PowerShell Remoting (NetOrk/netork#2899).
|
||||
|
||||
A fake transport replays what a run's script emits, one output object per line of
|
||||
tests/fixtures/synthetic/<run>.txt, through ``run_streaming``; the scripts end with a
|
||||
``napalm-exit-code:`` line, or say ``napalm-not-available:`` where the tool is missing.
|
||||
The fixtures are written from Microsoft's documented output, not recorded from a host.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
from napalm_device_types import HostRepairMixin, offered_host_repairs
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import repairs as mod
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
||||
|
||||
|
||||
def _fixture(name: str) -> list[str]:
|
||||
return (FIXTURES / name).read_text().split("\n")[:-1]
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""Replays *items* as the output objects of the next streamed script."""
|
||||
|
||||
def __init__(self, items: list[str], *, error: Exception | None = None) -> None:
|
||||
self.items = items
|
||||
self.error = error
|
||||
self.scripts: list[str] = []
|
||||
self.limits: list[float] = []
|
||||
self.is_open = True
|
||||
|
||||
def run_streaming(
|
||||
self, script: str, on_output: Callable[[str], None], *, limit: float
|
||||
) -> list[str]:
|
||||
self.scripts.append(script)
|
||||
self.limits.append(limit)
|
||||
for item in self.items:
|
||||
on_output(item)
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return list(self.items)
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _driver(items: list[str], **kwargs) -> tuple[WindowsDriver, FakeTransport]:
|
||||
transport = FakeTransport(items, **kwargs)
|
||||
driver = WindowsDriver("win01", "admin", "secret")
|
||||
driver._transport = transport # type: ignore[assignment]
|
||||
return driver, transport
|
||||
|
||||
|
||||
class TestCatalog:
|
||||
def test_the_driver_carries_the_contract(self):
|
||||
assert issubclass(WindowsDriver, HostRepairMixin)
|
||||
|
||||
def test_offers_the_checks_and_the_antimalware_runs_not_the_repairs(self):
|
||||
# sfc /scannow and DISM /RestoreHealth wait for a real-host test (#2899).
|
||||
assert offered_host_repairs(WindowsDriver) == [
|
||||
"verify_system_files",
|
||||
"check_component_store",
|
||||
"update_antimalware_signatures",
|
||||
"scan_antimalware",
|
||||
]
|
||||
|
||||
|
||||
class TestToolLines:
|
||||
def test_an_object_is_one_line(self):
|
||||
assert mod.tool_lines("Verification 52% complete.") == ["Verification 52% complete."]
|
||||
|
||||
def test_utf16_text_read_as_bytes_loses_its_nuls(self):
|
||||
# sfc writes UTF-16 to a redirected stdout; decoded byte by byte, each
|
||||
# character is followed by a NUL.
|
||||
raw = "Windows Resource Protection".encode("utf-16-le").decode("latin-1")
|
||||
assert "\x00" in raw
|
||||
assert mod.tool_lines(raw) == ["Windows Resource Protection"]
|
||||
|
||||
def test_a_byte_order_mark_is_dropped(self):
|
||||
assert mod.tool_lines("Beginning system scan.") == ["Beginning system scan."]
|
||||
|
||||
def test_carriage_returns_split_progress_into_lines(self):
|
||||
assert mod.tool_lines("Verification 1% complete.\rVerification 2% complete.\r\n") == [
|
||||
"Verification 1% complete.",
|
||||
"Verification 2% complete.",
|
||||
]
|
||||
|
||||
def test_blank_lines_and_trailing_spaces_go(self):
|
||||
assert mod.tool_lines(" \r\n\nresult ") == ["result"]
|
||||
|
||||
|
||||
class TestVerifySystemFiles:
|
||||
def test_streams_the_lines_and_succeeds_on_exit_code_zero(self):
|
||||
driver, transport = _driver(_fixture("sfc_verifyonly.txt"))
|
||||
seen: list[str] = []
|
||||
|
||||
result = driver.verify_system_files(log=seen.append)
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["exit_code"] == 0
|
||||
assert seen[0] == "Beginning system scan. This process will take some time."
|
||||
assert seen[-1] == "Windows Resource Protection did not find any integrity violations."
|
||||
assert not any(line.startswith("napalm-") for line in seen)
|
||||
assert result["output"] == "\n".join(seen)
|
||||
|
||||
def test_runs_sfc_verifyonly_decoded_as_utf16(self):
|
||||
driver, transport = _driver(_fixture("sfc_verifyonly.txt"))
|
||||
|
||||
driver.verify_system_files()
|
||||
|
||||
script = transport.scripts[0]
|
||||
assert "'/verifyonly'" in script
|
||||
assert "System32\\sfc.exe" in script
|
||||
assert "[System.Text.Encoding]::Unicode" in script
|
||||
assert "/scannow" not in script
|
||||
assert transport.limits == [mod.SFC_LIMIT]
|
||||
|
||||
def test_utf16_output_with_nuls_reads_as_text(self):
|
||||
items = [
|
||||
line.encode("utf-16-le").decode("latin-1")
|
||||
for line in _fixture("sfc_verifyonly.txt")[:-1]
|
||||
] + ["napalm-exit-code:0"]
|
||||
driver, _ = _driver(items)
|
||||
|
||||
result = driver.verify_system_files()
|
||||
|
||||
assert "did not find any integrity violations" in result["output"]
|
||||
assert "\x00" not in result["output"]
|
||||
|
||||
def test_a_non_zero_exit_code_fails_with_the_last_lines(self):
|
||||
items = [
|
||||
"Beginning system scan. This process will take some time.",
|
||||
"Windows Resource Protection could not start the repair service.",
|
||||
"napalm-exit-code:1",
|
||||
]
|
||||
driver, _ = _driver(items)
|
||||
|
||||
result = driver.verify_system_files()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["exit_code"] == 1
|
||||
assert result["error"].endswith("could not start the repair service.")
|
||||
|
||||
def test_a_missing_tool_is_not_available_not_an_error(self):
|
||||
driver, _ = _driver(["napalm-not-available:sfc.exe"])
|
||||
|
||||
result = driver.verify_system_files()
|
||||
|
||||
assert result == {
|
||||
"success": False,
|
||||
"output": "",
|
||||
"exit_code": None,
|
||||
"error": "sfc.exe is not available on this host",
|
||||
}
|
||||
|
||||
def test_without_log_it_still_returns_the_output(self):
|
||||
driver, _ = _driver(_fixture("sfc_verifyonly.txt"))
|
||||
assert "Verification 100% complete." in driver.verify_system_files()["output"]
|
||||
|
||||
|
||||
class TestCheckComponentStore:
|
||||
def test_scans_health_in_english_and_succeeds(self):
|
||||
driver, transport = _driver(_fixture("dism_scanhealth.txt"))
|
||||
seen: list[str] = []
|
||||
|
||||
result = driver.check_component_store(log=seen.append)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "No component store corruption detected." in seen[-2]
|
||||
script = transport.scripts[0]
|
||||
assert "System32\\Dism.exe" in script
|
||||
assert "'/Online /Cleanup-Image /ScanHealth /English'" in script
|
||||
assert "RestoreHealth" not in script
|
||||
assert transport.limits == [mod.DISM_LIMIT]
|
||||
|
||||
def test_an_hresult_exit_code_fails_in_hex(self):
|
||||
driver, _ = _driver(_fixture("dism_scanhealth_failed.txt"))
|
||||
|
||||
result = driver.check_component_store()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["exit_code"] == 0x800F081F
|
||||
assert result["error"].startswith("DISM /ScanHealth ended with exit code 0x800F081F:")
|
||||
assert "dism.log" in result["error"]
|
||||
|
||||
|
||||
class TestAntimalwareSignatures:
|
||||
def test_updates_and_reports_the_versions(self):
|
||||
driver, transport = _driver(_fixture("defender_signature_update.txt"))
|
||||
seen: list[str] = []
|
||||
|
||||
result = driver.update_antimalware_signatures(log=seen.append)
|
||||
|
||||
assert result["success"] is True
|
||||
assert seen == [
|
||||
"Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
|
||||
"Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC",
|
||||
]
|
||||
script = transport.scripts[0]
|
||||
assert "Update-MpSignature" in script
|
||||
assert "Get-Command -Name Update-MpSignature" in script
|
||||
assert transport.limits == [mod.SIGNATURE_LIMIT]
|
||||
|
||||
def test_a_host_without_defender_says_so(self):
|
||||
driver, _ = _driver(["napalm-not-available:Microsoft Defender Antivirus"])
|
||||
|
||||
result = driver.update_antimalware_signatures()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["error"] == "Microsoft Defender Antivirus is not available on this host"
|
||||
|
||||
def test_a_refused_update_fails_with_its_reason(self):
|
||||
items = [
|
||||
"Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
|
||||
"Update-MpSignature failed: Virus and spyware definitions update was completed with errors.",
|
||||
"Signatures after: 1.401.1234.0, updated 2026-11-27 06:12 UTC",
|
||||
"napalm-exit-code:1",
|
||||
]
|
||||
driver, _ = _driver(items)
|
||||
|
||||
result = driver.update_antimalware_signatures()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "completed with errors" in result["error"]
|
||||
|
||||
|
||||
class TestScanAntimalware:
|
||||
def test_a_quick_scan_reports_what_it_found(self):
|
||||
driver, transport = _driver(_fixture("defender_quick_scan.txt"))
|
||||
seen: list[str] = []
|
||||
|
||||
result = driver.scan_antimalware(log=seen.append)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "Threats detected: 1" in seen
|
||||
script = transport.scripts[0]
|
||||
assert "Start-MpScan -ScanType QuickScan" in script
|
||||
assert transport.limits == [mod.QUICK_SCAN_LIMIT]
|
||||
|
||||
def test_a_full_scan_has_its_own_limit(self):
|
||||
driver, transport = _driver(["napalm-exit-code:0"])
|
||||
|
||||
driver.scan_antimalware(quick=False)
|
||||
|
||||
assert "Start-MpScan -ScanType FullScan" in transport.scripts[0]
|
||||
assert transport.limits == [mod.FULL_SCAN_LIMIT]
|
||||
|
||||
|
||||
class TestLimit:
|
||||
@pytest.mark.parametrize(
|
||||
("run", "bound"),
|
||||
[
|
||||
(lambda d, **kw: d.verify_system_files(**kw), mod.SFC_LIMIT),
|
||||
(lambda d, **kw: d.check_component_store(**kw), mod.DISM_LIMIT),
|
||||
(lambda d, **kw: d.update_antimalware_signatures(**kw), mod.SIGNATURE_LIMIT),
|
||||
(lambda d, **kw: d.scan_antimalware(**kw), mod.QUICK_SCAN_LIMIT),
|
||||
(lambda d, **kw: d.scan_antimalware(False, **kw), mod.FULL_SCAN_LIMIT),
|
||||
],
|
||||
)
|
||||
def test_a_callers_limit_tightens_the_bound_never_widens_it(self, run, bound):
|
||||
driver, transport = _driver(["napalm-exit-code:0"])
|
||||
|
||||
run(driver, limit=600)
|
||||
run(driver, limit=bound * 2)
|
||||
run(driver)
|
||||
|
||||
assert transport.limits == [600, bound, bound]
|
||||
|
||||
|
||||
class TestCutOff:
|
||||
def test_a_run_past_its_limit_fails_with_what_it_printed(self):
|
||||
driver, _ = _driver(
|
||||
["Beginning system scan.", "Verification 40% complete."],
|
||||
error=TimeoutError("The script did not end within 3600 seconds"),
|
||||
)
|
||||
|
||||
result = driver.verify_system_files()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["exit_code"] is None
|
||||
assert result["error"].startswith("sfc /verifyonly ended without an exit code:")
|
||||
assert "Verification 40% complete." in result["error"]
|
||||
assert result["error"].endswith("did not end within 3600 seconds")
|
||||
|
||||
def test_an_error_the_script_wrote_fails_the_run(self):
|
||||
driver, _ = _driver([], error=PowerShellError("Access is denied."))
|
||||
|
||||
result = driver.check_component_store()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["error"].endswith("Access is denied.")
|
||||
|
||||
def test_an_unreadable_exit_code_is_none(self):
|
||||
driver, _ = _driver(["done", "napalm-exit-code:"])
|
||||
assert driver.verify_system_files()["exit_code"] is None
|
||||
|
||||
def test_a_closed_connection_raises(self):
|
||||
driver = WindowsDriver("win01", "admin", "secret")
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
driver.verify_system_files()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"script",
|
||||
[
|
||||
mod._PS_SFC_VERIFY,
|
||||
mod._PS_DISM_SCAN,
|
||||
mod._PS_SIGNATURE_UPDATE,
|
||||
mod._PS_QUICK_SCAN,
|
||||
mod._PS_FULL_SCAN,
|
||||
],
|
||||
)
|
||||
def test_every_script_follows_the_conventions(script):
|
||||
assert "$ErrorActionPreference = 'Stop'" in script
|
||||
assert "napalm-exit-code:" in script
|
||||
assert "napalm-not-available:" in script
|
||||
# No restart and no restore point as a side effect of a run (#2899).
|
||||
for forbidden in ("Restart-Computer", "Checkpoint-Computer", "shutdown"):
|
||||
assert forbidden not in script
|
||||
@@ -11,6 +11,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
|
||||
from pypsrp.complex_objects import PSInvocationState
|
||||
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
|
||||
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
@@ -166,6 +167,113 @@ class TestRunLast:
|
||||
_transport().run_last("Restart-Computer")
|
||||
|
||||
|
||||
class _Pipeline:
|
||||
"""A PowerShell pipeline whose output arrives over several polls, as pypsrp's
|
||||
``begin_invoke``/``poll_invoke`` deliver a long-running script's."""
|
||||
|
||||
def __init__(self, batches, *, errors=(), never_ends=False):
|
||||
self.batches = [list(b) for b in batches]
|
||||
self.output: list = []
|
||||
self.state = PSInvocationState.NOT_STARTED
|
||||
self.had_errors = bool(errors)
|
||||
self.streams = type("Streams", (), {"error": list(errors)})()
|
||||
self.never_ends = never_ends
|
||||
self.polls: list = []
|
||||
self.stopped = False
|
||||
self.script = None
|
||||
|
||||
def add_script(self, script):
|
||||
self.script = script
|
||||
|
||||
def begin_invoke(self):
|
||||
self.state = PSInvocationState.RUNNING
|
||||
|
||||
def poll_invoke(self, timeout=None):
|
||||
self.polls.append(timeout)
|
||||
if self.batches:
|
||||
self.output.extend(self.batches.pop(0))
|
||||
if not self.batches and not self.never_ends:
|
||||
self.state = PSInvocationState.COMPLETED
|
||||
|
||||
def stop(self):
|
||||
self.stopped = True
|
||||
self.state = PSInvocationState.STOPPED
|
||||
|
||||
|
||||
class TestRunStreaming:
|
||||
"""A long-running script: each output line reaches the caller as the host prints it."""
|
||||
|
||||
def _open(self, psrp, pipeline, **overrides):
|
||||
psrp["ps"].return_value = pipeline
|
||||
t = _transport(**overrides)
|
||||
t.open()
|
||||
return t
|
||||
|
||||
def test_each_output_object_reaches_the_caller_as_it_arrives(self, psrp):
|
||||
pipeline = _Pipeline([["one"], [], ["two", None, "three"]])
|
||||
t = self._open(psrp, pipeline)
|
||||
seen: list[str] = []
|
||||
|
||||
out = t.run_streaming("sfc", seen.append, limit=60)
|
||||
|
||||
assert seen == ["one", "two", "three"]
|
||||
assert out == ["one", "two", "three"]
|
||||
assert pipeline.script == "sfc"
|
||||
|
||||
def test_each_poll_waits_less_than_a_read_of_the_connection(self, psrp):
|
||||
pipeline = _Pipeline([["a"], ["b"]])
|
||||
t = self._open(psrp, pipeline, timeout=60)
|
||||
|
||||
t.run_streaming("x", lambda _line: None, limit=600)
|
||||
|
||||
assert pipeline.polls and all(0 < p < 60 for p in pipeline.polls)
|
||||
|
||||
def test_a_short_connection_timeout_still_polls(self, psrp):
|
||||
pipeline = _Pipeline([["a"]])
|
||||
t = self._open(psrp, pipeline, timeout=5)
|
||||
|
||||
t.run_streaming("x", lambda _line: None, limit=600)
|
||||
|
||||
assert pipeline.polls == [2]
|
||||
|
||||
def test_the_error_stream_raises_after_the_output_was_passed_on(self, psrp):
|
||||
pipeline = _Pipeline([["started"]], errors=["Access is denied."])
|
||||
t = self._open(psrp, pipeline)
|
||||
seen: list[str] = []
|
||||
|
||||
with pytest.raises(PowerShellError, match="Access is denied"):
|
||||
t.run_streaming("x", seen.append, limit=60)
|
||||
assert seen == ["started"]
|
||||
|
||||
def test_a_script_past_its_limit_is_stopped(self, psrp):
|
||||
pipeline = _Pipeline([["working"]], never_ends=True)
|
||||
t = self._open(psrp, pipeline)
|
||||
clock = iter([0.0, 10.0, 70.0, 130.0])
|
||||
|
||||
with (
|
||||
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
|
||||
pytest.raises(TimeoutError, match="60 seconds"),
|
||||
):
|
||||
t.run_streaming("x", lambda _line: None, limit=60)
|
||||
assert pipeline.stopped is True
|
||||
|
||||
def test_stopping_a_pipeline_that_ended_meanwhile_still_times_out(self, psrp):
|
||||
pipeline = _Pipeline([["working"]], never_ends=True)
|
||||
pipeline.stop = lambda: (_ for _ in ()).throw(RuntimeError("not running"))
|
||||
t = self._open(psrp, pipeline)
|
||||
clock = iter([0.0, 61.0])
|
||||
|
||||
with (
|
||||
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
|
||||
pytest.raises(TimeoutError),
|
||||
):
|
||||
t.run_streaming("x", lambda _line: None, limit=60)
|
||||
|
||||
def test_before_open_raises_connection_closed(self):
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
_transport().run_streaming("x", lambda _line: None, limit=60)
|
||||
|
||||
|
||||
class TestClose:
|
||||
def test_close_closes_pool_and_connection(self, psrp):
|
||||
t = _transport()
|
||||
|
||||
+33
-6
@@ -1,12 +1,15 @@
|
||||
"""Record what the driver's PowerShell scripts emit on a real Windows host.
|
||||
|
||||
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
|
||||
python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure] [--runs]
|
||||
|
||||
Asks for the password, runs every getter script over one WinRM connection and
|
||||
writes the raw JSON to tools/harvest-out/<label>/<fixture>.json — the same file
|
||||
names as tests/fixtures/synthetic/. harvest-out/ is gitignored: scrub serials,
|
||||
MAC and IP addresses, host names, account names and SIDs before copying anything into
|
||||
tests/.
|
||||
MAC and IP addresses and host names before copying anything into tests/.
|
||||
|
||||
``--runs`` also records the repair runs' output (``RUNS``), one output object per
|
||||
line in <run>.txt. They take up to an hour together, and two of them act on the
|
||||
host: the Defender signature update and a quick scan.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +18,7 @@ import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
|
||||
from napalm_windows import WindowsDriver, login_accounts, login_sessions, scheduled_tasks, time_sync
|
||||
from napalm_windows import WindowsDriver, repairs, scheduled_tasks, time_sync
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -28,8 +31,14 @@ SCRIPTS = {
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
"login_accounts": login_accounts._PS_LOGIN_ACCOUNTS,
|
||||
"login_sessions": login_sessions._PS_LOGIN_SESSIONS,
|
||||
}
|
||||
|
||||
# Recorded only with --runs: streamed, long, and two of them change the host.
|
||||
RUNS = {
|
||||
"sfc_verifyonly": (repairs._PS_SFC_VERIFY, repairs.SFC_LIMIT),
|
||||
"dism_scanhealth": (repairs._PS_DISM_SCAN, repairs.DISM_LIMIT),
|
||||
"defender_signature_update": (repairs._PS_SIGNATURE_UPDATE, repairs.SIGNATURE_LIMIT),
|
||||
"defender_quick_scan": (repairs._PS_QUICK_SCAN, repairs.QUICK_SCAN_LIMIT),
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
@@ -42,6 +51,7 @@ def main() -> None:
|
||||
ap.add_argument("label", help="subdirectory name, e.g. server2022 or win11")
|
||||
ap.add_argument("--port", type=int, default=5986)
|
||||
ap.add_argument("--insecure", action="store_true", help="skip certificate validation")
|
||||
ap.add_argument("--runs", action="store_true", help="also record the repair runs (RUNS)")
|
||||
args = ap.parse_args()
|
||||
|
||||
driver = WindowsDriver(
|
||||
@@ -64,10 +74,27 @@ def main() -> None:
|
||||
else:
|
||||
print(f" {name}: {len(raw)} bytes")
|
||||
(target / f"{name}.json").write_text(raw + "\n")
|
||||
for name, (script, limit) in RUNS.items() if args.runs else ():
|
||||
_record_run(driver, target, name, script, limit)
|
||||
finally:
|
||||
driver.close()
|
||||
print(f"written to {target}")
|
||||
|
||||
|
||||
def _record_run(
|
||||
driver: WindowsDriver, target: pathlib.Path, name: str, script: str, limit: int
|
||||
) -> None:
|
||||
"""One repair run's output objects as the host sent them, NULs and all."""
|
||||
assert driver._transport is not None
|
||||
try:
|
||||
lines = driver._transport.run_streaming(script, lambda _line: None, limit=limit)
|
||||
except Exception as exc: # record the failure, keep harvesting
|
||||
lines = []
|
||||
print(f" {name}: FAILED — {exc}")
|
||||
else:
|
||||
print(f" {name}: {len(lines)} lines")
|
||||
(target / f"{name}.txt").write_text("".join(f"{line}\n" for line in lines))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user