From 89a52db1a51b3e476d88e7c2b16af8dbd565f972 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:54:25 +0100 Subject: [PATCH] feat(log-sources): the event channels as the host's log sources (NetOrk/netork#2897) WindowsLogSourcesMixin.get_log_sources lists every event channel that is switched on and holds records (Get-WinEvent -ListLog *) as a source of kind eventlog, named by its channel, with its .evtx file, size and last write. Analytic and debug channels are left out. README and CHANGELOG describe the services, host events and log sources readings. --- CHANGELOG.md | 17 +++ README.md | 36 ++++++- napalm_windows/event_channels.py | 85 +++++++++++++++ napalm_windows/windows.py | 2 + tests/fixtures/synthetic/event_channels.json | 11 ++ tests/test_event_channels.py | 103 +++++++++++++++++++ tools/harvest.py | 10 +- 7 files changed, 262 insertions(+), 2 deletions(-) create mode 100644 napalm_windows/event_channels.py create mode 100644 tests/fixtures/synthetic/event_channels.json create mode 100644 tests/test_event_channels.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 23eb7c0..8b7976a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- What the event log recorded that says something is wrong with the host + (NetOrk/netork#2897): `get_host_events(since=None)`, napalm-device-types' + `HostEventsMixin`. Unexpected shutdowns (Kernel-Power 41, EventLog 6008), bugchecks + with their stop code (1001), fatal and corrected hardware errors (WHEA-Logger 18, 19, + 47), disk and file system errors (disk 7 and 153, Ntfs 55), crashing programs + (Application Error 1000) and services that ended unexpectedly (Service Control + Manager 7031, 7034), over the last seven days by default, in one script of three + queries bounded by time and count. An empty log is no events, not an error + (`NoMatchingEventsFound` is caught); a query that fails names its kinds `unread`. +- The event channels as the host's log sources: `get_log_sources()` lists every channel + that is switched on and holds records as a source of kind `eventlog`, named by its + channel, with its `.evtx` file, size and last write (`Get-WinEvent -ListLog *`). + Analytic and debug channels are left out. +- `get_services()` says how each service's last run ended (`result`, `exit_code`, from + `Win32_Service.ExitCode` and `ServiceSpecificExitCode`), whether a trigger starts it + (`trigger_start`) and the account it runs as (`account`), so that an automatic service + that died is told from one stopped on purpose. It moves into `WindowsServicesMixin`. - 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 diff --git a/README.md b/README.md index cae0cc4..2b566d6 100644 --- a/README.md +++ b/README.md @@ -36,12 +36,14 @@ handshake once. | `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) | | `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) | | `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) | -| `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` | +| `get_services` / `manage_service` | `Win32_Service` (with `ExitCode`, `StartName`) and the services' `TriggerInfo` registry keys, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType`. See *Services* | | `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted | | `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) | | `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones | | `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) | | `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only | +| `get_host_events` | `Get-WinEvent -FilterXPath`, three bounded queries over the System and Application logs. See *Host events* | +| `get_log_sources` | `Get-WinEvent -ListLog *`: every event channel switched on and holding records, as kind `eventlog` | | `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* | `running_kernel` carries the full build including the update revision @@ -97,6 +99,38 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written. zone with summer time switched off reads as `None`; writing the zone switches it back on. +### Services + +How a service's last run ended is `Win32_Service.ExitCode`, said in systemd's words +(napalm-device-types' `ServiceDict.result`): `0` is `success`, `1077` (never started +since boot: a demand-start service, or a delayed one in the minutes after boot) is no +result, `1066` is `exit-code` with the service's own `ServiceSpecificExitCode`, any +other code `exit-code` with that code (`1067`: the process ended without being +stopped). Both codes leave the host as `[int64]`: they are UInt32, and an HRESULT +would not fit `[int]`. `trigger_start` is a `TriggerInfo` key under the service, read +once for all of them; `account` is `StartName`. + +### Host events + +napalm-device-types' `HostEventsMixin`: what the event log recorded that says +something is wrong with the host, over the last seven days unless the caller names a +start. One script, three queries, each an XPath filter from the start on, newest +first and bounded by count: + +| Query | Events | Bound | +|---|---|---| +| System, with messages | Kernel-Power 41 and EventLog 6008 (unexpected shutdown; 41's `BugcheckCode` as the stop code), WER-SystemErrorReporting 1001 (bugcheck, its stop code), WHEA-Logger 18 (fatal hardware error), disk 7 (bad block), Ntfs 55 (corruption, its volume) | 100 | +| System, without messages | WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (retried I/O, its disk), Service Control Manager 7031 and 7034 (a service that ended unexpectedly, its display name) | 500 | +| Application, without messages | Application Error 1000 (a program that crashed, its path) | 200 | + +`Get-WinEvent` throws `NoMatchingEventsFound` when nothing matches; each query +catches it as no events, and any other failure costs only that query, whose kinds the +reading names `unread`. A query that returned its bound names its kinds `capped`. +What an event is about comes from its properties, never from its message, which is in +the host's language; messages are read only for the rare events (Windows formats them +slowly) and cut to 300 characters. Which of them is worth a warning is the +application's to say. + Not yet: packages, Windows Update, health metrics, Hyper-V. See netork#300 for the plan. diff --git a/napalm_windows/event_channels.py b/napalm_windows/event_channels.py new file mode 100644 index 0000000..d3d0671 --- /dev/null +++ b/napalm_windows/event_channels.py @@ -0,0 +1,85 @@ +"""The event channels as the host's log sources (NetOrk/netork#2897). + +:class:`WindowsLogSourcesMixin` gives the driver ``get_log_sources`` in napalm-device-types' +shape (``LogSourcesDict``). A Windows host keeps no journal and its programs hold no log +files a reader could name: its logs are its event channels, each a source of kind +``eventlog`` named by its channel -- the name CrowdSec (``event_channel``) and Wazuh +(``eventchannel``) read it by -- with its ``.evtx`` file as ``path``. + +One script, ``Get-WinEvent -ListLog *``: every channel that is switched on and holds +records, with its file (``%SystemRoot%`` expanded), size, last write and type. A channel +the account may not open is skipped, not the reading. Analytic and debug channels are +trace sessions written to ``.etl`` files, which a log reader cannot follow, and are left +out. WinRM needs an administrator, who may open every other channel, the Security log +included, so the reading is ``attributed``. Where the logs go beyond the host (Windows +Event Forwarding, an agent) is not read: ``forwarding`` is None. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from napalm_device_types import LogSourceDict, LogSourcesDict, eventlog_source + +from napalm_windows._powershell import _as_list + +_PS_EVENT_CHANNELS = r""" +$ErrorActionPreference = 'Stop' +ConvertTo-Json -Compress -Depth 3 -InputObject @( + Get-WinEvent -ListLog * -ErrorAction SilentlyContinue | + Where-Object { $_.IsEnabled -and $_.RecordCount } | + ForEach-Object { + [pscustomobject]@{ + channel = $_.LogName + path = [Environment]::ExpandEnvironmentVariables([string]$_.LogFilePath) + size = $_.FileSize + modified = if ($_.LastWriteTime) { + ([DateTimeOffset]$_.LastWriteTime).ToUnixTimeSeconds() + } else { $null } + records = $_.RecordCount + type = [string]$_.LogType + } + } +) +""" + +#: Trace sessions, not logs: written to .etl files a reader cannot follow. +_TRACE_TYPES = frozenset({"analytic", "debug"}) + + +def _is_log(raw: dict[str, Any]) -> bool: + return ( + bool(raw.get("channel")) + and int(raw.get("records") or 0) > 0 + and str(raw.get("type") or "").lower() not in _TRACE_TYPES + ) + + +def _source(raw: dict[str, Any]) -> LogSourceDict: + size, modified = raw.get("size"), raw.get("modified") + return eventlog_source( + str(raw["channel"]), + str(raw["path"]) if raw.get("path") else None, + None if size is None else int(size), + None if modified is None else float(modified), + ) + + +class WindowsLogSourcesMixin: + """``get_log_sources``: the host's event channels; 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_log_sources(self) -> LogSourcesDict: + """Every event channel that is switched on and holds records, sorted by name. + + * attributed (bool) - always True: an administrator opens every channel + * journald (bool) - always False: Windows keeps event channels, not a journal + * sources (list) - one ``eventlog`` source per channel + * forwarding - None: where the logs go beyond the host is not read + """ + channels = [c for c in _as_list(self._run_ps(_PS_EVENT_CHANNELS)) if _is_log(c)] + sources = sorted((_source(c) for c in channels), key=lambda s: s.get("channel", "")) + return {"attributed": True, "journald": False, "sources": sources, "forwarding": None} diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index faf6675..b3aa0ce 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -27,6 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict from napalm_windows._powershell import _as_list, _ps_quote +from napalm_windows.event_channels import WindowsLogSourcesMixin from napalm_windows.host_events import WindowsHostEventsMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.services import WindowsServicesMixin @@ -253,6 +254,7 @@ class WindowsDriver( WindowsTimeSyncMixin, WindowsServicesMixin, WindowsHostEventsMixin, + WindowsLogSourcesMixin, OSDriver, ): """NAPALM driver for Windows Server 2016+ and Windows 10/11. diff --git a/tests/fixtures/synthetic/event_channels.json b/tests/fixtures/synthetic/event_channels.json new file mode 100644 index 0000000..99e7183 --- /dev/null +++ b/tests/fixtures/synthetic/event_channels.json @@ -0,0 +1,11 @@ +[ + {"channel": "Application", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Application.evtx", "size": 20975616, "modified": 1764499800, "records": 41233, "type": "Administrative"}, + {"channel": "Security", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Security.evtx", "size": 20975616, "modified": 1764499990, "records": 58812, "type": "Administrative"}, + {"channel": "System", "path": "C:\\Windows\\System32\\Winevt\\Logs\\System.evtx", "size": 20975616, "modified": 1764499950, "records": 30187, "type": "Administrative"}, + {"channel": "Microsoft-Windows-Sysmon/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Sysmon%4Operational.evtx", "size": 67113984, "modified": 1764499999, "records": 120044, "type": "Operational"}, + {"channel": "Microsoft-Windows-PowerShell/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-PowerShell%4Operational.evtx", "size": 15798272, "modified": null, "records": 9120, "type": "Operational"}, + {"channel": "Microsoft-Windows-Kernel-PnP/Device Management", "path": null, "size": 69632, "modified": 1764400000, "records": 12, "type": "Operational"}, + {"channel": "Microsoft-Windows-WMI-Activity/Debug", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-WMI-Activity%4Debug.etl", "size": 4096, "modified": 1764400000, "records": 3, "type": "Debug"}, + {"channel": "Microsoft-Windows-Kernel-Boot/Analytic", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Kernel-Boot%4Analytic.etl", "size": 4096, "modified": 1764400000, "records": 7, "type": "Analytic"}, + {"channel": "Microsoft-Windows-Empty/Operational", "path": "C:\\Windows\\System32\\Winevt\\Logs\\Microsoft-Windows-Empty%4Operational.evtx", "size": 69632, "modified": 1764400000, "records": 0, "type": "Operational"} +] diff --git a/tests/test_event_channels.py b/tests/test_event_channels.py new file mode 100644 index 0000000..23a6c6b --- /dev/null +++ b/tests/test_event_channels.py @@ -0,0 +1,103 @@ +"""The event channels as the host's log sources (NetOrk/netork#2897). + +A Windows host keeps its logs in event channels. ``Get-WinEvent -ListLog *`` names +every one with its ``.evtx`` file, size, last write and record count; a channel that +is switched on and holds records is a log the host writes. Analytic and debug +channels are trace sessions, not logs a reader can follow, and are left out. The +answer is the shape of tests/fixtures/synthetic/event_channels.json. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from napalm_windows import WindowsDriver +from napalm_windows import event_channels as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "event_channels.json" + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer + + +def _reading(answer: str | None = None) -> dict: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(FIXTURE.read_text() if answer is None else answer) + return d.get_log_sources() + + +class TestTheReading: + def test_read_as_an_administrator_without_a_journal(self): + reading = _reading() + assert (reading["attributed"], reading["journald"], reading["forwarding"]) == ( + True, + False, + None, + ) + + def test_every_channel_with_records_sorted_by_name(self): + assert [s["channel"] for s in _reading()["sources"]] == [ + "Application", + "Microsoft-Windows-Kernel-PnP/Device Management", + "Microsoft-Windows-PowerShell/Operational", + "Microsoft-Windows-Sysmon/Operational", + "Security", + "System", + ] + + def test_a_channel_is_an_eventlog_source(self): + sysmon = next(s for s in _reading()["sources"] if "Sysmon" in s["channel"]) + assert sysmon == { + "kind": "eventlog", + "path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx", + "unit": None, + "container_id": None, + "process": None, + "size": 67113984, + "modified": "2025-11-30T10:53:19+00:00", + "channel": "Microsoft-Windows-Sysmon/Operational", + } + + def test_what_the_host_did_not_say_is_none(self): + sources = {s["channel"]: s for s in _reading()["sources"]} + assert sources["Microsoft-Windows-PowerShell/Operational"]["modified"] is None + assert sources["Microsoft-Windows-Kernel-PnP/Device Management"]["path"] is None + + @pytest.mark.parametrize("left_out", ["Debug", "Analytic", "Empty"]) + def test_trace_sessions_and_empty_channels_are_left_out(self, left_out): + assert not any(left_out in s["channel"] for s in _reading()["sources"]) + + def test_a_single_channel_is_still_a_list(self): + one = json.loads(FIXTURE.read_text())[2] + assert [s["channel"] for s in _reading(json.dumps(one))["sources"]] == ["System"] + + def test_no_channel_is_no_sources(self): + assert _reading("")["sources"] == [] + + +class TestTheScript: + def test_lists_every_channel_once(self): + assert "Get-WinEvent -ListLog *" in mod._PS_EVENT_CHANNELS + + def test_a_channel_it_may_not_open_costs_only_that_channel(self): + assert "-ErrorAction SilentlyContinue" in mod._PS_EVENT_CHANNELS + + def test_only_channels_switched_on_and_holding_records(self): + assert "$_.IsEnabled -and $_.RecordCount" in mod._PS_EVENT_CHANNELS + + def test_the_file_is_named_as_it_is_on_disk(self): + assert "ExpandEnvironmentVariables" in mod._PS_EVENT_CHANNELS + + def test_a_list_goes_through_input_object(self): + assert "-InputObject @(" in mod._PS_EVENT_CHANNELS diff --git a/tools/harvest.py b/tools/harvest.py index 63fd8fa..5161c39 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -15,7 +15,14 @@ import getpass import pathlib import time -from napalm_windows import WindowsDriver, host_events, scheduled_tasks, services, time_sync +from napalm_windows import ( + WindowsDriver, + event_channels, + host_events, + scheduled_tasks, + services, + time_sync, +) from napalm_windows import windows as mod SCRIPTS = { @@ -29,6 +36,7 @@ SCRIPTS = { "scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS, "time_sync": time_sync._PS_TIME_SYNC, "host_events": host_events.host_events_script(time.time() - 7 * 86400), + "event_channels": event_channels._PS_EVENT_CHANNELS, } OUT = pathlib.Path(__file__).parent / "harvest-out"