Skip to content
Documentation

ETW sensor

This page is published from the agent repository. Edit on GitHub View source

sensor-windows (crates/sensors/windows/etw) is the primary Windows sensor. It runs one real-time ETW session with 14 providers enabled and turns their records into schema events. This page covers the session, the providers, threading and back-pressure. How events get their process identity, paths and container is in etw-enrichment.md.

Components

ModuleResponsibility
sensor.rsWindowsSensor: builds SharedState, cleans up orphaned sessions, starts the trace, runs the liveness loop
providers.rsOne builder per provider (GUID, keyword mask, callback). The callbacks filter, spend budgets and emit.
payload.rsHow the DNS, registry, PowerShell, WMI, .NET, SMB, LDAP and NTLM records become events, decided on their named fields alone (PayloadFields)
normalize.rsPure helpers: FILETIME conversion, NT and registry path rewriting, session-name generation, orphan selection, diagnosis text
etw_sessions.rsNative session enumeration (QueryAllTracesW) and provider-enablement lookup (EnumerateTraceGuidsEx)
budget.rsPidBudget (N events per process per window) and KeyDedup (one event per key per window)
amsi.rsAMSI buffer decoding and AmsiGate (hash dedup plus per-process budget)
cross_process.rsRemote-thread and LSASS-open filters
bits.rsBITS job tracking and the Microsoft-update host filter
zone_identifier.rsMark-of-the-web parsing, read-back worker and dedup
pid_cache.rs, long_path.rs, silo.rs, hcs.rs, winapi.rsIdentity and path enrichment, see etw-enrichment.md

Modules marked #[cfg(any(windows, test))] in lib.rs hold platform-independent logic and are unit-tested on Linux and macOS CI too. Only the ETW plumbing and Win32 calls are Windows-only.

Session lifecycle

WindowsSensor::run does the following, in order:

  1. Starts two worker threads: the Zone.Identifier reader and the silo resolver (see threading).
  2. Builds SharedState, seeds the pid store from a Toolhelp snapshot (seed_pid_store) and finds the system LSASS (find_lsass).
  3. Stops every orphaned session under the agent's prefix (stop_all_orphaned_sessions).
  4. Creates a session with a fresh random name and enables all providers on it (ferrisetw::UserTrace), through start_or_stop_session.
  5. Runs liveness_watch on the calling thread until stop() or a liveness failure.
  6. Stops the trace and deletes the canary file.

Session names and orphan cleanup

Named ETW sessions are kernel objects. They outlive the process that created them, so after a crash or taskkill /f the session is still running, and a restart with the same name would fail with AlreadyExist. The sensor therefore:

  • names each session <prefix><random suffix> (random_session_name). The prefix comes from the agent (EtwNames, wtrace- today) because this crate cannot read the agent's identity constants. The random suffix keeps the name from being a fixed, documented kill target. It is not a secret: an attacker can list sessions by the same prefix.
  • at startup, enumerates running sessions with QueryAllTracesW (running_sessions) and stops every one under the prefix. No state is persisted between runs, so this catches any number of orphans from consecutive unclean shutdowns.
  • falls back to parsing logman query -ets (parse_orphaned_sessions) when QueryAllTracesW fails, or when its 64-entry buffer came back full and may have hidden sessions (select_orphaned_sessions). The parser takes the first column only, which logman never translates, so it works on any display language.
  • stops the session itself if start_and_process fails half-way (start_or_stop_session). ferrisetw creates the session before enabling providers, and a failure after that point returns without a Drop that would stop it. Without this, each retry by the watchdog would leak one live session.

Single-instance assumption. Cleanup stops every session under the prefix, including one that belongs to another live agent instance. This is correct only while at most one agent runs per host. Two overlapping instances would blind the older one, which its own liveness check then reports. The check for "another instance is running" would have to live in the agent or watchdog, since this crate depends only on schema.

Providers

All providers are enabled on the one session. "Keywords" is the match-any mask passed to ferrisetw; when it is not set, ferrisetw enables every keyword of the provider.

ProviderKeywordsEvent IDs keptEmitsVolume control
Kernel-Process0x4070 (process, thread, image, job/silo)1 start, 2 end, 3 thread start, 5 image load, 23-26 siloExec, ImageLoad, RemoteThread4 (thread stop) dropped on its id; image loads only for tracked pids
Kernel-Audit-API-Callsnone declared by the manifest5 PsOpenProcessProcessAccessonly opens of LSASS with a memory-reaching right; dedup
Kernel-Networkall42/12 TCP v4, 58/26 TCP v6, 14 UDP send v4Connect, UdpSendConnectDedup per flow
Kernel-File0x80 | 0x400 | 0x100012 create, 30 create-new, 26 delete-pathFileOpen, FileDelete, FileQuarantine (via worker)tracked pids only, read-only opens dropped, deletes only for Zone.Identifier
DNS-Clientall3008 query completedDnsQuerynone
Kernel-Registryall4 RegSetValueKeyRegistrySetwrites only
PowerShellall4104 script blockScriptBlocknone (each fragment is one event)
AMSIall1101 scanAmsiContentAmsiGate
LDAP-Clientall30 searchLdapSearchPidBudget 128 per 10 s
NTLMall4020-4023, 4026, 4027NtlmAuthKeyDedup 60 s
WMI-Activityall23 ExecQuery, 24 ExecMethodWmiActivitynone
DotNETRuntimeall154 AssemblyLoad, dynamic onlyAssemblyLoadfile-backed loads dropped
SMBClientall30704 connectedSmbConnectnone
Bits-Clientall16403, 4, 5, 61BitsJobMicrosoft update hosts dropped

GUIDs, keyword constants and per-provider field notes (field names and types as observed on specific Windows builds) are in providers.rs. ALL_PROVIDERS lists them by name for the blind-session diagnosis.

Provider-specific behavior worth knowing:

  • Process start. process_provider reads the real command line from the target's PEB, since ProcessStart does not carry it. It falls back to the image path when the read fails, never to a placeholder. argv is left empty (Windows has a flat command line) and hashes, signatures and version-resource fields are filled later by the agent's enrichment stage.
  • Network. TcpClient emits no EID 42, so EID 12 (send) also counts as a connect. ConnectDedup keys on (pid, sport, daddr, dport) over 60 s, so a connection produces one Connect while parallel connections stay distinct. Receives are not used: they would count the same connection on the receiver side.
  • File. Only pids in the pid store produce events, which removes pure kernel activity and untracked churn. The create disposition (high byte of CreateOptions) is mapped to POSIX-style O_WRONLY|O_CREAT flags by disposition_to_flags so file rules are shared with Linux; a read-only open (flags 0) is dropped. General delete and rename semantics are not available from this provider; they come from the minifilter.
  • Mark-of-the-web. A create on file:Zone.Identifier is queued for a background read-back (MarkQueue); a delete of that stream (Unblock-File, T1553.005) becomes a FileDelete of the stream path (forward_mark_removal). The stream check runs on the raw path first, so the expensive path normalization and token lookup only run for the rare match. Details in etw-enrichment.md.
  • PowerShell 4104. Long scripts are split by the provider into fragments sharing a ScriptBlockId. Each fragment is its own ScriptBlock event; consumers reassemble on script_block_id + message_number.
  • AMSI 1101. The buffer is decoded as UTF-16LE text (decode_text), capped at 16 Ki characters with a text_truncated flag. Buffers with more than 10 % control characters (assemblies, VBA p-code) are not reported as text.
  • Registry 4. Only REG_SZ and REG_EXPAND_SZ data is decoded (registry_set); other types carry no value. Key paths are rewritten to HKLM\.../HKU\... by normalize_registry_key.
  • BITS. The BITS service does the network I/O, so the job's client process is reported as the actor. See etw-enrichment.md.

Threading

flowchart TB
    subgraph kernel["ETW session (kernel buffers)"]
    end
    kernel --> CB["ferrisetw consumer thread<br/>all provider callbacks"]
    CB -->|sink.on_event| SINK[(EventSink)]
    CB -->|MarkQueue.offer<br/>bounded 256| ZR["zone-identifier-reader thread"]
    ZR --> SINK
    CB -->|silo_requests.try_send<br/>bounded 16| SR["silo-resolver thread<br/>(Host Compute Service)"]
    SR -->|SiloDirectory| CB
    RUN["run thread: liveness_watch<br/>writes canary every 2 s"] -.->|reads events_seen| CB
  • Consumer thread. ferrisetw delivers every record of every provider on one thread. Anything slow done in a callback delays every provider and, if it lasts, makes ETW drop buffers. That is why callbacks avoid network round trips (UNC paths are never resolved or opened, see image_identity_is_capturable and long_path), defer normalization until a record is known to be interesting, and move file reads and HCS calls to workers.
  • Shared state. SharedState holds every cache and gate behind its own Mutex, plus the events_seen atomic counter.
  • Workers exit on their own when the last sender is dropped (the trace's callbacks and SharedState), so they are not joined.

Bounds and back-pressure

The sensor never blocks the consumer thread waiting for a consumer. Every queue is bounded with try_send, and every map has a cap.

StructureBoundAt the boundConstant
Pid store16,384 pidsLRU batch eviction of 1/8, countedPID_CACHE_CAP
8.3 directory cache4,096 dirscleared, countedLONG_PATH_CACHE_CAP
Mark read-back queue256 marksmark dropped, countedMARK_QUEUE_CAPACITY
Quarantine dedup5 s window, 1,024 pathsreported without dedupQUARANTINE_DEDUP_WINDOW_NS
Silo lookup requests16dropped, asked again on the silo's next eventSILO_REQUEST_CAPACITY
AMSIdedup 300 s on AMSI's SHA-256 (4,096 hashes), 64 per process per 10 srefused, countedDEDUP_WINDOW_NS, PER_PID_LIMIT
LDAP128 per process per 10 srefused, countedLDAP_PER_PID_LIMIT
NTLMone per (direction, account, target, address, version) per 60 sduplicate countedNTLM_DEDUP_WINDOW_NS
Remote threadsone per (creator, owner, 64 KiB start bucket) per 60 s; 32 per creator per 10 srefused, countedREMOTE_THREAD_*
LSASS opensone per (caller, mask, status) per 60 sduplicate countedLSASS_OPEN_DEDUP_WINDOW_NS
Connect dedup60 s per flowduplicate suppressedConnectDedup
BITS1,024 jobs, 200 files per joboldest forgotten, countedMAX_TRACKED_JOBS, MAX_FILES_PER_JOB

PidBudget and KeyDedup in budget.rs share one design: a map capped at 1,024 pids or 4,096 keys. When the map is full, expired entries are pruned first. If it is still full of live entries, the whole map is cleared and the number of forgotten entries is added to flushed. A flush means some processes get a fresh budget early, or some repeats get reported twice: more volume, never a lost event. Refusals and flushes are logged when the counter crosses a power of two, so a sustained flood writes O(log n) lines.

KeyDedup::is_repeat and record are separate so a caller can check the budget between them: a remote thread refused by the budget does not mark its key as seen, so an injector spending its budget on decoys does not also silence the pair it was refused on.

Liveness canary and blind-session diagnosis

A quiet host produces no guaranteed ETW events, so "no events for 30 s" alone would not tell a healthy idle host from a stopped trace. liveness_watch makes it deterministic:

  • every 2 s it writes a canary file in the temp directory (<canary prefix><pid>). The agent's own pid is in the pid store and the write passes the Kernel-File filter, so it must produce an event. The file provider drops canary events before emitting them.
  • the Kernel-Process, Kernel-Network and Kernel-File callbacks increment events_seen. If it does not move for 15 consecutive checks (30 s), run returns an error.

The error message is built by silent_session_diagnosis so the operator knows where to look:

  • Is our session still listed? "Stopped from outside" and "running but blind" need different investigations (describe_silent_session). A truncated native listing cannot prove absence, so in that case logman is asked (listing_is_conclusive).
  • Our own loss counters (EventsLost, RealTimeBuffersLost, LogBuffersLost) from QueryAllTracesW (describe_session_losses).
  • Foreign sessions that enable our providers, from provider_enablements, at most three named (describe_foreign_sessions). A real-time session with no buffer written is flagged: a real-time session that nobody consumes stalls real-time delivery for every consumer on the host, which has been observed to blind this sensor.

The agent then restarts nothing by itself: the run returns the error, hold_after_primary keeps the supplementary sensors alive, and the windows-etw heartbeat raises the silence alert.

Failure modes

FailureBehavior
Not elevatedstart_and_process fails, any half-created session is stopped, run returns ETW startup error.
Session stopped from outside (logman stop)Canary silence for 30 s, error with diagnosis. Loud, not silent.
Session starved by a foreign real-time sessionSame, with the foreign session named.
logman missingOrphan fallback and diagnosis degrade to "unknown"; logged.
A Win32 enrichment call failsOne field degrades (User::Unknown, image path as command line, no container); the event is still emitted. See etw-enrichment.md.
TDH cannot find a schema for a recordRecord skipped (locator.event_schema error).
ETW drops buffers under pressureProcessEnd records can be lost, which is why the pid store has an LRU backstop. Loss counts appear in the diagnosis only.

Configuration

The sensor has no configuration file of its own. The agent passes EtwNames:

FieldValue todayConstraint
session_prefixwtrace-Must stay the same across starts on a host, or orphans of the previous prefix are never stopped.
canary_prefixsynthaea-canary-Followed by the agent pid, in %TEMP%.

Everything else (provider set, keyword masks, budgets, windows) is a constant in sensor.rs, providers.rs and the gate modules.

Capabilities reported

WindowsSensor::capabilities claims exec, file, connect, user attribution and parent lineage. It does not claim auth events: logons come from the Event Log sensor.

Testing

  • Unit tests on every OS for the pure modules: normalize, payload, budget, amsi, cross_process, bits, zone_identifier, silo, pid_cache, long_path, and the identity helpers in lib.rs.
  • Never-panic suite tests/robustness.rs: seeded pseudo-random bytes into zone_identifier::parse and bits::is_microsoft_update_url, both of which read attacker-chosen input on the consumer thread.
  • Real-session tests, #[ignore] because they need an elevated Windows process: kernel_process_keyword_mask.rs and kernel_file_keyword_mask.rs check that the providers honor the keyword masks the sensor relies on.
  • Payload decoding of the DNS, registry, PowerShell, WMI, .NET, SMB, LDAP and NTLM records is tested in payload against an in-memory PayloadFields, including a property test that arbitrary field values of any type never panic. What those tests cannot check is that a provider really writes the field names and types they assume: those come from lab captures, recorded as field notes in providers.rs.
  • Clippy for this crate must be run with --target x86_64-pc-windows-msvc; host-only clippy does not compile the Windows-gated modules.

Known gaps

  • Kernel-Network, Kernel-Registry, DNS-Client, PowerShell, WMI, DotNETRuntime and the other user-mode providers are enabled with every keyword. Filtering happens on the event id in the callback, after the record has been delivered.
  • Injection without a new thread (APC, thread hijack), handle duplication into LSASS and kernel-mode activity are not visible to ETW from a non-PPL session. They need the driver work tracked in #32 and #27.
  • The image file identity is taken in the ProcessStart callback, so a rename-and-replace faster than ETW delivery still wins: #46.