Skip to content

Check eventlog wevtapi - #504

Open
inqrphl wants to merge 5 commits into
mainfrom
check-eventlog-wevtapi
Open

inqrphl wants to merge 5 commits into
mainfrom
check-eventlog-wevtapi

Conversation

@inqrphl

@inqrphl inqrphl commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Warning

AI-generated code. This change was implemented with AI assistance. Please review the implementation, tests, and behavior carefully before merging.

Summary

check_eventlog no longer uses WMI. It enumerates every registered Windows event log channel through wevtapi.dll and reads events with the native Windows Event Log API.

This makes Applications and Services Logs visible to the check. For example, Microsoft-Windows-Fault-Tolerant-Heap/Operational is now found; the WMI backend could not see that channel at all.

Motivation

WMI Win32_NTLogEvent only exposes classic, registry-backed logs such as Application, System, and Security. Modern channels defined by provider manifests are not part of that store. A check targeting Microsoft-Windows-Fault-Tolerant-Heap/Operational therefore returned OK - No entries found, even though Event Viewer showed the event.

The native API also removes the WMI/RPC overhead and the WQL translation layer.

What changed

  • The event log backend now lives in pkg/snclient/check_eventlog_windows.go.
  • pkg/eventlog is removed.
  • pkg/snclient/check_eventlog_query_windows.go and the WQL filter translation are removed.
  • All registered channels are enumerated by default. Use channel= to limit the check to selected channels.
  • Filters are still applied to the returned events. A matcher slice applies event-codes and the generic filter before the message is rendered when possible.
  • Event messages are rendered only for events that survive the matchers, unless the filter itself uses message.
  • event-codes keeps the old AND-of-ORs behavior.
  • Docs and tests are updated. No new Go module dependencies were added.

wevtapi functions

The DLL is loaded with windows.NewLazySystemDLL("wevtapi.dll").

Function Use
EvtOpenChannelEnum Open the system channel enumerator.
EvtNextChannelPath Read each registered channel name.
EvtQuery Open a result set for one channel with an XPath query.
EvtNext Fetch a batch of event handles from the result set.
EvtCreateRenderContext Define the System value paths once per query.
EvtRender Render EvtRenderEventValues into EVT_VARIANT values. No XML parsing.
EvtOpenPublisherMetadata Open and cache provider metadata for messages.
EvtFormatMessage Render the human-readable message text.
EvtClose Close the channel enumerator, result set, render context, publisher metadata, and event handles.

EvtQuery is called with EvtQueryChannelPath and EvtQueryForwardDirection. The time limit is part of the XPath:

*[System[TimeCreated[timediff(@SystemTime) <= N]]]

N is the scan range in milliseconds. Forward direction keeps the previous oldest-first order.

EvtRender uses EvtRenderEventValues; the value paths are:

Event/System/Provider/@Name
Event/System/EventID
Event/System/Level
Event/System/TimeCreated/@SystemTime
Event/System/Channel
Event/System/Computer
Event/System/Keywords

The values are read through a 16-byte evtVariant structure and small accessors for strings, unsigned integers, and FILETIME values.

Event flow

  1. Enumerate all channels with EvtOpenChannelEnum and EvtNextChannelPath.
  2. For each channel, open a result set with EvtQuery.
  3. Fetch event handles in batches with EvtNext.
  4. Render the system values with EvtRender.
  5. Apply the event-codes matcher and, when the filter does not need the message, the generic filter matcher.
  6. For matching events, format the message with EvtFormatMessage.
  7. Append the event to the check list and close the handle.
  8. Close the result set, render context, and publisher metadata.

Channel errors are skipped. If no channel can be read at all, the first error is returned.

Channel and provider aliases

The old names are kept, and new preferred names are added:

Preferred Legacy aliases
channel file, log
provider source

channel works both as an argument and as a filter attribute:

check_eventlog channel='Microsoft-Windows-Fault-Tolerant-Heap/Operational'
check_eventlog filter="channel = 'Microsoft-Windows-Fault-Tolerant-Heap/Operational'"

All old checks keep working:

check_eventlog file=Application
check_eventlog filter="file = 'Application'"
check_eventlog filter="source = 'MSSQL'"

The defaults now use the preferred names:

detail-syntax: %(channel) %(provider) (%(message))
unique-index:  %(channel)-%(provider)-%(id)

The rendered output and unique-index grouping are unchanged, because channel and provider expand to the same values as file and source.

Internally the event fields are also named Channel and Provider.

Compatibility

  • Existing arguments and filter keywords are unchanged.
  • file, log, and source remain supported aliases.
  • event-codes keeps the previous AND-of-ORs semantics.
  • scan-range, truncate-message, unique-index, and show-all are unchanged.
  • level keeps the WMI-compatible mapping: levels 1 and 2 are error, 3 is warning, 4 is information, 5 is verbose. Audit success/failure is derived from the Windows keywords.
  • eventidentifier continues to expose the event ID.
  • Events are still returned oldest-first.

Performance

  • No WMI query construction or RPC calls.
  • The time window is applied by the Event Log service through the XPath filter.
  • Message rendering is the expensive part. Events that cannot match are dropped before EvtFormatMessage; messages are only rendered for matching events unless the filter references message.
  • event-codes is applied before message rendering, even when the generic filter needs the message.
  • On the test machine (Windows 10 Pro 24H2), a default all-channel 24-hour scan takes about 2 seconds. The Fault-Tolerant-Heap channel over 6 days takes about 1.6 seconds.

Limitations

  • All registered channels are queried by default. On Windows 11 that is around 1300 channels.
  • Analytic and Debug channels may be disabled or not readable with EvtQuery; their errors are skipped.
  • The Security channel still requires the agent to have read access.
  • Events whose provider has no message metadata render an empty message; EvtFormatMessage has nothing to resolve in that case.

Testing

  • go build ./pkg/snclient
  • go test -run 'TestCheckEventlog|TestEventlog|TestEvtVariant' ./pkg/snclient
  • Windows 386 and Linux cross-builds.
  • Manual check of the Fault-Tolerant-Heap event with the original source like 'Fault-Tolerant' command.
  • Manual checks of channel, file, log, source, and provider.
  • golangci-lint reports no findings in the changed files; go vet is clean.

New tests cover channel enumeration, event reading, unknown channels, level mapping, event-codes parsing, the channel alias, and evtVariant value extraction.

Read all registered event log channels through wevtapi.dll. This makes Applications and Services Logs visible without WMI.

Keep the backend in check_eventlog_windows.go and remove pkg/eventlog, together with the WQL filter translation. Keep the existing check arguments and filters. Event messages are rendered only for matching events.
Use the event batch for the EvtNext array and check ERROR_NO_MORE_ITEMS before treating a zero return value as an error. The inlined call previously passed the event slice and panicked on the first empty batch.
@inqrphl

inqrphl commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

This change from WMI to wevtapi is required if we want to get logs that are found in "Applications and services logs" .

I tried to minimize the total line changes, so most of the DLL calls are inlined into the two main functions: getEventLog and getEventLogChannels.

GetEventLog is long, but it cant be any shorter without increasing the total line count. Publisher cache and render context could have been initialized/kept elsewhere but that would spread the logic around and increase LOC .

I explicitly asked AI to rename args/attributes "file" -> "channel" and "source" -> "provider", turn "file" and "source" into aliases of "channel" and "provider" . But that was the last commit, and I can revert it if you do not want it @sni

@inqrphl

inqrphl commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Failing CI tests are due to Github, there is an acknowledged outage.

Unrelated to the code changes.

| event-codes | Event codes to query. SNClient combines comma-separated values with OR. Valid range: 0-65535. You can repeat this option. |
| file | File to read. Repeat this option to check multiple files. |
| log | Alias for file |
| channel | Event log channel to read. Repeat this option to check multiple channels. |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

like i said in the comment, the additions of new args/attributes are done in a single comment and can be reverted

procEvtClose = wevtapiDll.NewProc("EvtClose")
)

// getEventLogChannels returns all event log channels registered on the system.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The term in the new api is channels. Includes the defualt windows log:
HKLM\SYSTEM\CurrentControlSet\Services\EventLog<LogName>

and whatever other application logs registered themselves under:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers{GUID}
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Channels<ChannelName>

Thats why I renamed the "file" to channels . One provider can provide multiple channels, which can point to different files:
Microsoft-Windows-CloudStore/Initialization
Microsoft-Windows-CloudStore/Operational

// If matchers is empty, all messages are rendered.
//
//nolint:funlen // the query setup is inlined into the event loop
func getEventLog(ctx context.Context, channel string, newerThan time.Time, matchers []func(*eventLogEvent) bool) ([]eventLogEvent, error) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the main function of the PR.

I deliberately had it argument based on a channel. So that typical user who might only want one channel/file can use it without querying every channel.

Inside the channel, we only filter using xpath based time filter. Only with the time filter, the queries are fast enough. Way faster than the WMI it is replacing anyway.

PR description has some numbers for it.

return nil, fmt.Errorf("eventlog query, file: '%s' , got an error: %w", file, res.err)
}
// eventLogEvent is a single entry read from a Windows event log channel.
type eventLogEvent struct {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are way more details we can get using the wevtapi.dll , but I did not add them.

Especially the "file". In my view, it should point to full path of the backing .evtx logfile, but that would be confused by the "channel" here.

@inqrphl
inqrphl marked this pull request as ready for review November 26, 2026 13:23
@inqrphl
inqrphl requested a review from sni November 26, 2026 13:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant