diff --git a/napalm_windows/services.py b/napalm_windows/services.py new file mode 100644 index 0000000..aa6cdf0 --- /dev/null +++ b/napalm_windows/services.py @@ -0,0 +1,98 @@ +"""The host's services, and how each one's last run ended (NetOrk/netork#2897). + +:class:`WindowsServicesMixin` reads ``get_services`` for the driver, which carries +the script across ``PsrpTransport.run``. + +One script: every ``Win32_Service`` with its state, start mode and process, the +account it runs as (``StartName``) and the code its last run ended with +(``ExitCode``). Both exit codes are UInt32 and leave the host as ``[int64]``, since +``[int]`` would throw on an HRESULT and fail the reading. Which services a trigger +starts (a device arriving, a network change, a request) is one registry read for all +of them: the ``TriggerInfo`` keys under ``HKLM:\\SYSTEM\\CurrentControlSet\\Services``. + +**How the last run ended** is said in systemd's words (napalm-device-types' +``ServiceDict.result``), so that one rule reads it for every host: + +* ``0`` is ``success``: running, or stopped on purpose. +* ``1077`` (``ERROR_SERVICE_NEVER_STARTED``) is no result: not started since the + host booted -- a demand-start service, or a delayed one in the minutes after boot. +* ``1066`` (``ERROR_SERVICE_SPECIFIC_ERROR``) is ``exit-code`` with the service's own + code, ``ServiceSpecificExitCode``. +* Any other code is ``exit-code`` with that code: ``1067`` is a process that ended + without being stopped. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict + +from napalm_windows._powershell import _as_list + +_PS_SERVICES = r""" +$ErrorActionPreference = 'Stop' +$triggered = @{} +$keys = 'HKLM:\SYSTEM\CurrentControlSet\Services\*\TriggerInfo' +Get-Item -Path $keys -ErrorAction SilentlyContinue | + ForEach-Object { $triggered[(Split-Path -Path $_.PSParentPath -Leaf)] = $true } +ConvertTo-Json -Compress -Depth 3 -InputObject @( + Get-CimInstance -ClassName Win32_Service | ForEach-Object { + [pscustomobject]@{ + name = $_.Name + state = [string]$_.State + start_mode = [string]$_.StartMode + pid = [int]$_.ProcessId + exit_code = [int64]$_.ExitCode + service_code = [int64]$_.ServiceSpecificExitCode + account = $_.StartName + trigger_start = [bool]$triggered[$_.Name] + } + } +) +""" + +_ENABLED_START_MODES = {"auto", "boot", "system"} +#: ``ERROR_SERVICE_NEVER_STARTED``: no attempt to start it since the host booted. +_NEVER_STARTED = 1077 +#: ``ERROR_SERVICE_SPECIFIC_ERROR``: the code is the service's own. +_SERVICE_SPECIFIC = 1066 + + +def _result(raw: dict[str, Any]) -> tuple[str | None, int | None]: + """How the last run ended, and its code where that was not success.""" + code = raw.get("exit_code") + if code is None or int(code) == _NEVER_STARTED: + return None, None + if int(code) == 0: + return SERVICE_RESULT_SUCCESS, None + if int(code) == _SERVICE_SPECIFIC and raw.get("service_code"): + return SERVICE_RESULT_EXIT_CODE, int(raw["service_code"]) + return SERVICE_RESULT_EXIT_CODE, int(code) + + +def _service(raw: dict[str, Any]) -> ServiceDict: + running = str(raw.get("state") or "").lower() == "running" + result, exit_code = _result(raw) + return { + "name": str(raw["name"]), + "running": running, + "enabled": str(raw.get("start_mode") or "").lower() in _ENABLED_START_MODES, + "pid": int(raw.get("pid") or 0) if running else 0, + "result": result, + "exit_code": exit_code, + "trigger_start": bool(raw.get("trigger_start")), + "account": str(raw["account"]) if raw.get("account") else None, + } + + +class WindowsServicesMixin: + """``get_services`` from ``Win32_Service``; the driver carries the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_ps(self, script: str) -> Any: ... + + def get_services(self) -> list[ServiceDict]: + """Every service with whether it runs, starts at boot, and how its last run ended.""" + return [_service(s) for s in _as_list(self._run_ps(_PS_SERVICES))] diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index fbd26dd..1a88734 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -24,10 +24,11 @@ from typing import Any from napalm.base.exceptions import ConnectionClosedException from napalm_device_types import FingerprintRule, OSDriver, PortSpec -from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict +from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict from napalm_windows._powershell import _as_list, _ps_quote from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin +from napalm_windows.services import WindowsServicesMixin from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport @@ -123,20 +124,6 @@ ConvertTo-Json -Compress -Depth 3 -InputObject @( ) """ -_PS_SERVICES = r""" -$ErrorActionPreference = 'Stop' -ConvertTo-Json -Compress -Depth 3 -InputObject @( - Get-CimInstance -ClassName Win32_Service | ForEach-Object { - [pscustomobject]@{ - name = $_.Name - state = [string]$_.State - start_mode = [string]$_.StartMode - pid = [int]$_.ProcessId - } - } -) -""" - # Every listening TCP and bound UDP socket, the processes holding them and the # services those processes run. Sockets owned by http.sys (WinRM, IIS) belong to # the System process; a shared svchost runs several services in one process. @@ -201,7 +188,6 @@ _ROUTE_PROTOCOLS = { "rip": "rip", } -_ENABLED_START_MODES = {"auto", "boot", "system"} _DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"} @@ -261,7 +247,9 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): +class WindowsDriver( + WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsServicesMixin, OSDriver +): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: @@ -489,20 +477,6 @@ class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): # Services # ------------------------------------------------------------------ - def get_services(self) -> list[ServiceDict]: - services: list[ServiceDict] = [] - for s in _as_list(self._run_ps(_PS_SERVICES)): - running = (s.get("state") or "").lower() == "running" - services.append( - { - "name": s["name"], - "running": running, - "enabled": (s.get("start_mode") or "").lower() in _ENABLED_START_MODES, - "pid": int(s.get("pid") or 0) if running else 0, - } - ) - return services - def get_listening_sockets(self) -> ListeningSocketsDict: """Every listening TCP and bound UDP socket, with the process and the Windows service behind it (``Get-NetTCPConnection``, ``Get-NetUDPEndpoint``, diff --git a/tests/fixtures/synthetic/services.json b/tests/fixtures/synthetic/services.json index a57bcd7..981ff1a 100644 --- a/tests/fixtures/synthetic/services.json +++ b/tests/fixtures/synthetic/services.json @@ -1,7 +1,11 @@ [ - {"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234}, - {"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0}, - {"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321}, - {"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0}, - {"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null} + {"name": "WinRM", "state": "Running", "start_mode": "Auto", "pid": 1234, "exit_code": 0, "service_code": 0, "account": "NT AUTHORITY\\NetworkService", "trigger_start": false}, + {"name": "Spooler", "state": "Stopped", "start_mode": "Manual", "pid": 0, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": false}, + {"name": "MSSQL$SQLEXPRESS", "state": "Running", "start_mode": "Auto", "pid": 4321, "exit_code": 0, "service_code": 0, "account": "CORP\\svc-sql", "trigger_start": false}, + {"name": "RemoteRegistry", "state": "Stopped", "start_mode": "Disabled", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "NT AUTHORITY\\LocalService", "trigger_start": true}, + {"name": "wuauserv", "state": "Stopped", "start_mode": "Manual", "pid": null, "exit_code": 0, "service_code": 0, "account": "LocalSystem", "trigger_start": true}, + {"name": "AppReadiness", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1077, "service_code": 0, "account": "LocalSystem", "trigger_start": false}, + {"name": "BackupAgent", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1067, "service_code": 0, "account": "CORP\\svc-backup", "trigger_start": false}, + {"name": "VendorSync", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1066, "service_code": 2147942405, "account": "LocalSystem", "trigger_start": false}, + {"name": "BthServ", "state": "Stopped", "start_mode": "Auto", "pid": 0, "exit_code": 1, "service_code": 0, "account": null, "trigger_start": true} ] diff --git a/tests/test_services.py b/tests/test_services.py new file mode 100644 index 0000000..637eddd --- /dev/null +++ b/tests/test_services.py @@ -0,0 +1,125 @@ +"""The host's services and how each one's last run ended (NetOrk/netork#2897). + +``Win32_Service`` says whether a service runs and how it starts, and also what its +last run ended with: ``ExitCode`` (``1066`` hands over to +``ServiceSpecificExitCode``, ``1077`` is "not started since boot"). Together with +whether a trigger starts it (a ``TriggerInfo`` key under the service) that tells a +service that died from one stopped on purpose. The reading is the shape of +tests/fixtures/synthetic/services.json. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from napalm_windows import WindowsDriver +from napalm_windows import services as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "services.json" + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer if script == mod._PS_SERVICES else "" + + +def _services(answer: str | None = None) -> dict[str, dict]: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer) + return {s["name"]: s for s in d.get_services()} + + +class TestRunningAndEnabled: + def test_maps_state_and_start_mode(self): + services = _services() + assert {n: (s["running"], s["enabled"], s["pid"]) for n, s in services.items()} == { + "WinRM": (True, True, 1234), + "Spooler": (False, False, 0), + "MSSQL$SQLEXPRESS": (True, True, 4321), + "RemoteRegistry": (False, False, 0), + "wuauserv": (False, False, 0), + "AppReadiness": (False, True, 0), + "BackupAgent": (False, True, 0), + "VendorSync": (False, True, 0), + "BthServ": (False, True, 0), + } + + def test_a_single_service_is_still_a_list(self): + one = json.loads(FIXTURE.read_text())[0] + assert list(_services(json.dumps(one))) == ["WinRM"] + + def test_nothing_read_is_no_services(self): + assert _services("") == {} + + +class TestHowTheLastRunEnded: + def test_a_running_service_succeeded(self): + assert _services()["WinRM"] == { + "name": "WinRM", + "running": True, + "enabled": True, + "pid": 1234, + "result": "success", + "exit_code": None, + "trigger_start": False, + "account": "NT AUTHORITY\\NetworkService", + } + + def test_one_stopped_on_purpose_succeeded(self): + assert (_services()["Spooler"]["result"], _services()["Spooler"]["exit_code"]) == ( + "success", + None, + ) + + def test_one_not_started_since_boot_has_no_result(self): + """1077: a delayed or a demand-start service that has not run yet.""" + service = _services()["AppReadiness"] + assert (service["result"], service["exit_code"]) == (None, None) + + def test_one_that_died_ended_with_its_exit_code(self): + """1067: the process terminated unexpectedly.""" + service = _services()["BackupAgent"] + assert (service["result"], service["exit_code"]) == ("exit-code", 1067) + + def test_a_service_specific_error_is_the_services_own_code(self): + service = _services()["VendorSync"] + assert (service["result"], service["exit_code"]) == ("exit-code", 2147942405) + + def test_a_trigger_start_service_says_so(self): + assert _services()["BthServ"]["trigger_start"] is True + assert _services()["BackupAgent"]["trigger_start"] is False + + def test_the_account_it_runs_as(self): + assert _services()["BackupAgent"]["account"] == "CORP\\svc-backup" + assert _services()["BthServ"]["account"] is None + + def test_a_reading_without_the_new_fields_says_nothing_of_them(self): + """An older script's answer: running and enabled only, nothing invented.""" + old = [{"name": "WinRM", "state": "Stopped", "start_mode": "Auto", "pid": 0}] + service = _services(json.dumps(old))["WinRM"] + assert (service["result"], service["exit_code"], service["trigger_start"]) == ( + None, + None, + False, + ) + + +class TestTheScript: + def test_exit_codes_leave_the_host_as_wide_integers(self): + """``ServiceSpecificExitCode`` is a UInt32: ``[int]`` would throw on an HRESULT.""" + assert "[int64]$_.ExitCode" in mod._PS_SERVICES + assert "[int64]$_.ServiceSpecificExitCode" in mod._PS_SERVICES + + def test_trigger_start_is_read_once_from_the_registry(self): + assert r"Services\*\TriggerInfo" in mod._PS_SERVICES + assert "-ErrorAction SilentlyContinue" in mod._PS_SERVICES + + def test_a_list_goes_through_input_object(self): + assert "-InputObject @(" in mod._PS_SERVICES diff --git a/tests/test_windows.py b/tests/test_windows.py index 8e3f6ec..ca3e27c 100644 --- a/tests/test_windows.py +++ b/tests/test_windows.py @@ -370,19 +370,6 @@ class TestGetRouteTo: assert list(routes) == ["192.168.50.0/24"] -class TestGetServices: - def test_maps_state_and_start_mode(self): - services = _driver(_PS_SERVICES=_fixture("services.json")).get_services() - - assert services == [ - {"name": "WinRM", "running": True, "enabled": True, "pid": 1234}, - {"name": "Spooler", "running": False, "enabled": False, "pid": 0}, - {"name": "MSSQL$SQLEXPRESS", "running": True, "enabled": True, "pid": 4321}, - {"name": "RemoteRegistry", "running": False, "enabled": False, "pid": 0}, - {"name": "wuauserv", "running": False, "enabled": False, "pid": 0}, - ] - - class TestGetListeningSockets: """netOrk #673: what listens, and which Windows service it is.""" diff --git a/tools/harvest.py b/tools/harvest.py index 38de2f4..7385719 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -14,7 +14,7 @@ import argparse import getpass import pathlib -from napalm_windows import WindowsDriver, scheduled_tasks, time_sync +from napalm_windows import WindowsDriver, scheduled_tasks, services, time_sync from napalm_windows import windows as mod SCRIPTS = { @@ -23,7 +23,7 @@ SCRIPTS = { "interfaces_ip": mod._PS_INTERFACES_IP, "arp": mod._PS_ARP, "routes": mod._PS_ROUTES, - "services": mod._PS_SERVICES, + "services": services._PS_SERVICES, "listening": mod._PS_LISTENING, "scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS, "time_sync": time_sync._PS_TIME_SYNC,