From 21a21383ff26865ffd31a1a50b5ba4cc8a5ecc9c Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:53:13 +0100 Subject: [PATCH] feat(host-events): the event log's shutdowns, crashes, hardware and disk errors (NetOrk/netork#2897) WindowsHostEventsMixin.get_host_events(since=None) reads, in one script, three bounded queries over the window: the System log's rare events (Kernel-Power 41, EventLog 6008, WER-SystemErrorReporting 1001, WHEA-Logger 18, disk 7, Ntfs 55) with their messages, its frequent ones (WHEA-Logger 19/47, disk 153, Service Control Manager 7031/7034) and the Application log's crashes (Application Error 1000). Each query catches NoMatchingEventsFound; one that fails names its kinds unread, one read up to its bound names them capped. --- napalm_windows/host_events.py | 254 ++++++++++++++++++++++ napalm_windows/windows.py | 7 +- tests/fixtures/synthetic/host_events.json | 217 ++++++++++++++++++ tests/test_host_events.py | 206 ++++++++++++++++++ tools/harvest.py | 4 +- 5 files changed, 686 insertions(+), 2 deletions(-) create mode 100644 napalm_windows/host_events.py create mode 100644 tests/fixtures/synthetic/host_events.json create mode 100644 tests/test_host_events.py diff --git a/napalm_windows/host_events.py b/napalm_windows/host_events.py new file mode 100644 index 0000000..aa90074 --- /dev/null +++ b/napalm_windows/host_events.py @@ -0,0 +1,254 @@ +"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897). + +:class:`WindowsHostEventsMixin` implements napalm-device-types' +:class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries +the script across ``PsrpTransport.run``. + +**One script, three queries**, each an XPath filter over a fixed set of providers and +event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and +bounded by count: + +* *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008 + (an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss), + WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a + fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption); +* *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger + 19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control + Manager 7031 and 7034 (a service that ended unexpectedly); +* *apps*, the Application log without messages: Application Error 1000 (a program that + crashed, its path the eleventh property). + +``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under +``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query +catches it as no events. 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** is taken from its properties, which do not depend on the +host's language, never from its message, which does: the stop code, the disk or volume, +the program's path (its name on a Windows that records no path), the service's display +name. The message is kept as the host wrote it, cut short. +""" + +from __future__ import annotations + +import time +from collections.abc import Callable +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any + +from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin +from napalm_device_types import host_event as _event +from napalm_device_types.host_events import ( + APP_CRASH, + DISK_ERROR, + HARDWARE_ERROR_CORRECTED, + HARDWARE_ERROR_FATAL, + HOST_EVENT_MESSAGE_CHARS, + HOST_EVENT_WINDOW_DAYS, + SERVICE_CRASH, + SYSTEM_CRASH, + UNEXPECTED_SHUTDOWN, +) + +from napalm_windows._powershell import _as_list + +_KERNEL_POWER = "Microsoft-Windows-Kernel-Power" +_BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting" +_WHEA = "Microsoft-Windows-WHEA-Logger" +_SCM = "Service Control Manager" +_APP_ERROR = "Application Error" + + +def _bugcheck(props: list[str]) -> str | None: + """Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none.""" + word = props[0].strip() if props else "" + return f"0x{int(word):08x}" if word.isdigit() and int(word) else None + + +def _stop_code(props: list[str]) -> str | None: + """1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``.""" + word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else "" + return word or None + + +def _first(props: list[str]) -> str | None: + return props[0] if props else None + + +def _program(props: list[str]) -> str | None: + """Application Error 1000: its path where the host records one, else its name.""" + path = props[10] if len(props) > 10 else "" + return path.strip() or _first(props) + + +def _none(props: list[str]) -> str | None: + return None + + +_Subject = Callable[[list[str]], str | None] + +#: (provider, event ID) -> the kind and what the event is about. +_EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = { + (_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck), + ("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none), + (_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code), + (_WHEA, 18): (HARDWARE_ERROR_FATAL, _none), + (_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none), + (_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none), + ("disk", 7): (DISK_ERROR, _first), + ("disk", 153): (DISK_ERROR, _first), + ("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first), + ("Ntfs", 55): (DISK_ERROR, _first), + (_SCM, 7031): (SERVICE_CRASH, _first), + (_SCM, 7034): (SERVICE_CRASH, _first), + (_APP_ERROR, 1000): (APP_CRASH, _program), +} + +#: Each query's log, its events, its bound and whether it reads their messages. +_QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = { + "rare": ( + "System", + ( + (_KERNEL_POWER, 41), + ("EventLog", 6008), + (_BUGCHECK, 1001), + (_WHEA, 18), + ("disk", 7), + ("Microsoft-Windows-Ntfs", 55), + ("Ntfs", 55), + ), + 100, + True, + ), + "frequent": ( + "System", + ((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)), + 500, + False, + ), + "apps": ("Application", ((_APP_ERROR, 1000),), 200, False), +} + +#: The kinds each query reads, in the order of HOST_EVENT_KINDS. +_PART_KINDS: dict[str, tuple[str, ...]] = { + part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events}) + for part, (_log, events, _max, _message) in _QUERIES.items() +} + +# Q runs one query: its events with their properties as strings, or why not. +# $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure. +_PS_QUERY = rf""" +$ErrorActionPreference = 'Stop' +function Q($log, $xpath, $max, $withMessage) {{ + try {{ + $rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{ + $m = $null + if ($withMessage) {{ + try {{ $m = [string]$_.Message }} catch {{ $m = $null }} + if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{ + $m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS}) + }} + }} + [pscustomobject]@{{ + provider = $_.ProviderName + id = [int]$_.Id + time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds() + props = @($_.Properties | Select-Object -First 11 | + ForEach-Object {{ [string]$_.Value }}) + message = $m + }} + }}) + [pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }} + }} catch {{ + if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{ + [pscustomobject]@{{ ok = $true; capped = $false; events = @() }} + }} else {{ + [pscustomobject]@{{ + ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message + }} + }} + }} +}} +""" + + +def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str: + which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events) + return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]" + + +def host_events_script(since: float) -> str: + """The reading's script, from *since* (unix seconds) on.""" + start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z") + lines = [_PS_QUERY] + parts = [] + for part, (log, events, bound, message) in _QUERIES.items(): + lines.append(f'${part} = "{_xpath(events, start)}"') + parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})") + lines.append("[pscustomobject]@{ parts = [pscustomobject]@{") + lines.extend(parts) + lines.append("} } | ConvertTo-Json -Compress -Depth 6") + return "\n".join(lines) + "\n" + + +def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None: + known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0))) + if known is None: + return None + kind, subject = known + props = [str(p) for p in _as_list(raw.get("props"))] + source = f"{source_log}: {raw.get('provider')} {raw.get('id')}" + return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message")) + + +def _part(answer: Any, log: str) -> list[HostEventDict] | None: + """One query's events; None when it was not read.""" + if not isinstance(answer, dict) or not answer.get("ok"): + return None + found = (_parse_event(e, log) for e in _as_list(answer.get("events"))) + return [e for e in found if e is not None] + + +def _in_order(kinds: set[str]) -> list[str]: + return [k for k in HOST_EVENT_KINDS if k in kinds] + + +def _reading(raw: Any, since: float) -> HostEventsDict: + if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict): + raise ValueError("the host events reading came back without a report") + events: list[HostEventDict] = [] + capped: set[str] = set() + unread: set[str] = set() + for part, (log, _events, _bound, _message) in _QUERIES.items(): + answer = raw["parts"].get(part) + found = _part(answer, log) + if found is None: + unread.update(_PART_KINDS[part]) + continue + if answer.get("capped"): + capped.update(_PART_KINDS[part]) + events.extend(found) + events.sort(key=lambda e: e["time"], reverse=True) + return { + "since": datetime.fromtimestamp(since, UTC).isoformat(), + "events": events, + "capped": _in_order(capped), + "unread": _in_order(unread), + } + + +class WindowsHostEventsMixin(HostEventsMixin): + """The event log's warnings-worthy events; 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_host_events(self, since: float | None = None) -> HostEventsDict: + """The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default + over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module. + + :raises ValueError: when the reading came back without a report. + """ + start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since + return _reading(self._run_ps(host_events_script(start)), start) diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index 1a88734..faf6675 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.host_events import WindowsHostEventsMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.services import WindowsServicesMixin from napalm_windows.time_sync import WindowsTimeSyncMixin @@ -248,7 +249,11 @@ def _is_noise_route(destination: str) -> bool: class WindowsDriver( - WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsServicesMixin, OSDriver + WindowsScheduledJobsMixin, + WindowsTimeSyncMixin, + WindowsServicesMixin, + WindowsHostEventsMixin, + OSDriver, ): """NAPALM driver for Windows Server 2016+ and Windows 10/11. diff --git a/tests/fixtures/synthetic/host_events.json b/tests/fixtures/synthetic/host_events.json new file mode 100644 index 0000000..93cd342 --- /dev/null +++ b/tests/fixtures/synthetic/host_events.json @@ -0,0 +1,217 @@ +{ + "parts": { + "rare": { + "ok": true, + "capped": false, + "events": [ + { + "provider": "Microsoft-Windows-WER-SystemErrorReporting", + "id": 1001, + "time": 1764470150, + "props": [ + "0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50)", + "C:\\Windows\\MEMORY.DMP", + "1130-01" + ], + "message": "The computer has rebooted from a bugcheck. The bugcheck was: 0x0000009f (0x0000000000000003, 0xffffc40f1a2b3c40, 0xfffff80412345678, 0xffffc40f1a2b3d50). A dump was saved in: C:\\Windows\\MEMORY.DMP. Report Id: 1130-01." + }, + { + "provider": "EventLog", + "id": 6008, + "time": 1764470040, + "props": [ + "03:12:09", + "\u200e30.\u200e11.\u200e2026", + "", + "", + "1234", + "", + "" + ], + "message": "The previous system shutdown at 03:12:09 on 30.11.2026 was unexpected." + }, + { + "provider": "Microsoft-Windows-Kernel-Power", + "id": 41, + "time": 1764470035, + "props": [ + "159", + "3", + "18446676388826430528", + "18446735294628329080", + "18446676388826430800", + "false", + "0" + ], + "message": "The system has rebooted without cleanly shutting down first." + }, + { + "provider": "Microsoft-Windows-WHEA-Logger", + "id": 18, + "time": 1764383600, + "props": [ + "1", + "0", + "5", + "0", + "0" + ], + "message": "A fatal hardware error has occurred." + }, + { + "provider": "disk", + "id": 7, + "time": 1764466400, + "props": [ + "\\Device\\Harddisk1\\DR1" + ], + "message": "The device, \\Device\\Harddisk1\\DR1, has a bad block." + }, + { + "provider": "Microsoft-Windows-Ntfs", + "id": 55, + "time": 1764462800, + "props": [ + "D:", + "\\Device\\HarddiskVolume5", + "0x2" + ], + "message": "A corruption was discovered in the file system structure on volume D:." + }, + { + "provider": "Microsoft-Windows-Kernel-Power", + "id": 41, + "time": 1764297200, + "props": [ + "0", + "0", + "0", + "0", + "0", + "false", + "0" + ], + "message": null + } + ] + }, + "frequent": { + "ok": true, + "capped": false, + "events": [ + { + "provider": "Service Control Manager", + "id": 7031, + "time": 1764470600, + "props": [ + "Backup Agent", + "1", + "60000", + "1", + "Restart the service" + ], + "message": null + }, + { + "provider": "Microsoft-Windows-WHEA-Logger", + "id": 47, + "time": 1764470500, + "props": [ + "3", + "0", + "1" + ], + "message": null + }, + { + "provider": "disk", + "id": 153, + "time": 1764470400, + "props": [ + "\\Device\\Harddisk1\\DR1", + "0x1d4c0", + "1", + "\\Device\\00000034" + ], + "message": null + }, + { + "provider": "Service Control Manager", + "id": 7034, + "time": 1764470300, + "props": [ + "Vendor Sync", + "2" + ], + "message": null + }, + { + "provider": "Microsoft-Windows-WHEA-Logger", + "id": 19, + "time": 1764470200, + "props": [ + "3", + "0", + "1" + ], + "message": null + } + ] + }, + "apps": { + "ok": true, + "capped": false, + "events": [ + { + "provider": "Application Error", + "id": 1000, + "time": 1764470900, + "props": [ + "vendorapp.exe", + "4.2.0.0", + "65a1b2c3", + "ntdll.dll", + "10.0.20348.2340", + "f0e1d2c3", + "c0000005", + "00000000000a1b2c", + "1f40", + "01db1234567890ab", + "C:\\Program Files\\Vendor\\vendorapp.exe" + ], + "message": null + }, + { + "provider": "Application Error", + "id": 1000, + "time": 1764470800, + "props": [ + "vendorapp.exe", + "4.2.0.0", + "65a1b2c3", + "ntdll.dll", + "10.0.20348.2340", + "f0e1d2c3", + "c0000005", + "00000000000a1b2c", + "1f40", + "01db1234567890ab", + "C:\\Program Files\\Vendor\\vendorapp.exe" + ], + "message": null + }, + { + "provider": "Application Error", + "id": 1000, + "time": 1764470700, + "props": [ + "legacy.exe", + "1.0.0.0", + "5f0a0b0c" + ], + "message": null + } + ] + } + } +} diff --git a/tests/test_host_events.py b/tests/test_host_events.py new file mode 100644 index 0000000..c858ef9 --- /dev/null +++ b/tests/test_host_events.py @@ -0,0 +1,206 @@ +"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897). + +One script asks the event log three questions over the reading's window: the rare +events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware +error, a bad block, a file system corruption), its frequent ones (corrected +hardware errors, retried disk I/O, services that ended unexpectedly) and the +Application log's crashing programs. Each is bounded by time and count, and each +catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The +answer is the shape of tests/fixtures/synthetic/host_events.json. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any + +import pytest +from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin + +from napalm_windows import WindowsDriver +from napalm_windows import host_events as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json" +NOW = 1764500000.0 +WEEK = 7 * 86400 + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer + + +def _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver: + if answer is None: + answer = FIXTURE.read_text() + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer)) + return d + + +def _fixture() -> dict[str, Any]: + return json.loads(FIXTURE.read_text()) + + +@pytest.fixture(autouse=True) +def _now(monkeypatch): + monkeypatch.setattr(mod.time, "time", lambda: NOW) + + +def _kinds(reading) -> list[tuple[str, str | None]]: + return [(e["kind"], e["subject"]) for e in reading["events"]] + + +class TestTheEvents: + def test_every_event_as_its_kind_and_subject_newest_first(self): + assert _kinds(_driver().get_host_events()) == [ + ("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"), + ("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"), + ("app_crash", "legacy.exe"), + ("service_crash", "Backup Agent"), + ("hardware_error_corrected", None), + ("disk_error", r"\Device\Harddisk1\DR1"), + ("service_crash", "Vendor Sync"), + ("hardware_error_corrected", None), + ("system_crash", "0x0000009f"), + ("unexpected_shutdown", None), + ("unexpected_shutdown", "0x0000009f"), + ("disk_error", r"\Device\Harddisk1\DR1"), + ("disk_error", "D:"), + ("hardware_error_fatal", None), + ("unexpected_shutdown", None), + ] + + def test_an_event_says_when_where_and_what_the_host_wrote(self): + crash = next( + e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash" + ) + assert crash == { + "kind": "system_crash", + "time": "2025-11-30T02:35:50+00:00", + "subject": "0x0000009f", + "source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001", + "message": crash["message"], + } + assert crash["message"].startswith("The computer has rebooted from a bugcheck.") + + def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self): + shutdowns = [ + e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown" + ] + assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None] + + def test_the_hosts_message_is_cut(self): + answer = _fixture() + answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000 + events = _driver(answer).get_host_events()["events"] + assert max(len(e["message"] or "") for e in events) == 300 + + def test_an_event_the_reading_does_not_know_is_left_out(self): + answer = _fixture() + answer["parts"]["rare"]["events"] = [ + {"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []} + ] + kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]} + assert "unexpected_shutdown" not in kinds + + def test_a_single_event_is_still_a_list(self): + answer = _fixture() + answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0] + apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"] + assert len(apps) == 1 + + +class TestWhatWasRead: + def test_a_full_reading_names_nothing_capped_or_unread(self): + reading = _driver().get_host_events() + assert (reading["capped"], reading["unread"]) == ([], []) + + def test_an_empty_log_is_no_events_not_an_error(self): + """What the script makes of ``NoMatchingEventsFound``: read, nothing found.""" + answer = _fixture() + for part in answer["parts"].values(): + part["events"] = [] + reading = _driver(answer).get_host_events() + assert (reading["events"], reading["unread"]) == ([], []) + + def test_a_query_that_failed_names_its_kinds_unread(self): + answer = _fixture() + answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"} + reading = _driver(answer).get_host_events() + assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"] + assert "service_crash" not in {e["kind"] for e in reading["events"]} + + def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self): + answer = _fixture() + answer["parts"]["apps"]["capped"] = True + assert _driver(answer).get_host_events()["capped"] == ["app_crash"] + + def test_a_part_missing_from_the_answer_is_unread(self): + answer = _fixture() + del answer["parts"]["apps"] + assert _driver(answer).get_host_events()["unread"] == ["app_crash"] + + def test_every_kind_is_read_by_some_query(self): + read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds} + assert read == set(HOST_EVENT_KINDS) + + @pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}']) + def test_an_answer_without_a_report_raises(self, answer): + with pytest.raises(ValueError): + _driver(answer).get_host_events() + + +class TestTheWindow: + def test_a_week_by_default(self): + d = _driver() + reading = d.get_host_events() + assert reading["since"] == "2025-11-23T10:53:20+00:00" + assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0] + + def test_the_callers_start(self): + d = _driver() + reading = d.get_host_events(since=NOW - 3600) + assert reading["since"] == "2025-11-30T09:53:20+00:00" + assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0] + + +class TestTheScript: + script = mod.host_events_script(NOW - WEEK) + + def test_every_query_catches_no_matching_events(self): + assert self.script.count("Get-WinEvent") == 1 + assert "NoMatchingEventsFound" in self.script + assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3 + + def test_every_query_is_bounded_by_count(self): + bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)] + assert bounds == [100, 500, 200] + assert "-MaxEvents $max" in self.script + + def test_every_query_is_bounded_by_time(self): + assert self.script.count("TimeCreated[@SystemTime>=") == 3 + + def test_only_the_rare_events_carry_their_message(self): + assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [ + "true", + "false", + "false", + ] + + def test_the_answer_survives_a_deep_object(self): + assert "-Depth 6" in self.script + + def test_stops_on_errors_it_does_not_catch(self): + assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'") + + def test_the_driver_carries_the_contract(self): + assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin) diff --git a/tools/harvest.py b/tools/harvest.py index 7385719..63fd8fa 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -13,8 +13,9 @@ from __future__ import annotations import argparse import getpass import pathlib +import time -from napalm_windows import WindowsDriver, scheduled_tasks, services, time_sync +from napalm_windows import WindowsDriver, host_events, scheduled_tasks, services, time_sync from napalm_windows import windows as mod SCRIPTS = { @@ -27,6 +28,7 @@ SCRIPTS = { "listening": mod._PS_LISTENING, "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), } OUT = pathlib.Path(__file__).parent / "harvest-out"