WESP: MS's New Way to Build EDRs

hey, it’s DbgMan again. this time no bug, but something maybe cooler: MS quietly shipped an EDR engine inside Windows. a Rust kernel driver called
wesp.systhat watches processes, threads, files, registry, handles… and can block all of it. no hardcoded detections, just a rule engine waiting for someone to program it. so I reversed the driver and its SDK to find out what it sees, what it can block, and who’s allowed to drive it :)
TL;DR
The driver (wesp.sys)
wesp.sysis a Rust minifilter that turns almost every interesting kernel event (process, thread, image load, handle, registry, file, pipe, mailslot, volume, KTM) into a typed event and pushes it through a rule engine.- It does not hardcode detections. Clients (security products) connect over
\EspFilterPort, upload rules (filters compiled to a BDD), and receive notifications. Rules can also enforce:- block process creation (
CreationStatus) - block registry operations
- fail file I/O (
FLT_PREOP_COMPLETE) - strip access from file opens and process/thread/desktop handles
- block process creation (
- Who may connect is gated by a token security attribute,
WESP://Permission. The highest privilege level also requires the caller to be PPL Antimalware. - The whole driver sits behind two WIL feature flags: it refuses to load (
STATUS_NOT_SUPPORTED) unless both are on.
The client SDK (espclient.dll)
espclient.dllis the SDK a security product uses to drivewesp.sys. It exports 124 C functions (Esp*).- It is a C++ shell over a Rust core:
client\dll\api.cpp,client\lib\{core,client,rule,rustrule,eventqueue,service,message}.cpp→espclient_rs(Rust). - Function split: ~630 Rust (
espclient_rs,bdd,string_match; 18.rspaths), ~577 C++ (Esp::*,wil::), ~309 C/CRT. - What each side does: the exported API, SCM and transport are C++; rule validation, BDD compilation and pattern matching are Rust.
- The DLL compiles rules on the client side. Filters become a BDD (
espclient_rs::bdd::RuleBddBuilder), string patterns become an NFA/trie (string_match), and the result is serialised into oneFilterSendMessageper update. - Transport is plain Filter Manager:
FilterConnectCommunicationPort(L"\\EspFilterPort"),FilterSendMessage, andFilterGetMessageon a thread-pool I/O for events. - The DLL itself enforces no security. All authorisation happens in the driver, which checks the token claim
WESP://Permissionand PPL Antimalware. Loading this DLL in an arbitrary process gets you nothing. - Every API is wrapped in a TraceLogging activity (
WespClientProvider::<ApiName>), so client activity is fully ETW-traceable.
Symbols: wesp.pdb is on the public symbol server (5FF3A3E025DC4E938206D6514BE6572A1). After loading it, 4295 of 4344 functions were named. The remaining 49 were all statically linked Rust core/alloc runtime (formatting, panics, allocator) and are renamed rust_* in the IDB. espclient.dll had 13 unnamed panic/alloc thunks, also renamed. Zero sub_ left in either binary.
Part 1: wesp.sys, the kernel driver
Architecture overview

Let’s get into the reversing.

The full sensor surface of wesp.sys, named straight from the PDB.
The driver won’t even load unless Microsoft flips it on
DriverEntry (0x180001000) does three gate checks before anything else:
InitSafeBootMode != 0→ return immediately (no WESP in Safe Mode).RtlQueryFeatureConfiguration(54098957)→g_Feature_54098957_EnabledRtlQueryFeatureConfiguration(61161283)→g_Feature_61161283_Enabled
The default state byte next to each ID decides what happens when no override exists: 2 = enabled by default, 1 = disabled by default, 0 = always off.
| Feature ID | Default state byte | Meaning |
|---|---|---|
54098957 |
2 |
enabled by default |
61161283 |
1 |
disabled by default: needs a staged rollout or an override to enable |
If either evaluates false, DriverEntry returns 0xC00000BB (STATUS_NOT_SUPPORTED). After that it registers the ETW TraceLogging provider Microsoft.Windows.WESP.Driver.



WESP is a feature-staged component: two velocity IDs gate the whole driver.
Sensor registration
ps::register_ps_notify_routines<EspCore> (0x180036E40):
| API | Routine | Event(s) produced |
|---|---|---|
PsSetCreateProcessNotifyRoutineEx2(0, …) |
ps::create_process_notify 0x180035280 |
ProcessCreate, ProcessTerminate |
PsSetCreateThreadNotifyRoutineEx(1 = Subsystems) |
ps::create_thread_notify_subsystems 0x180036EF0 |
ThreadCreate, ThreadTerminate |
PsSetCreateThreadNotifyRoutineEx(0 = NonSystem) |
ps::create_thread_notify_nonsystem 0x180038020 |
ThreadStart |
PsSetLoadImageNotifyRoutineEx(…, 1) |
ps::load_image_notify 0x180038810 |
ProcessLoadImage |
Plus:
ob::register_callback(0x180047580) →ObRegisterCallbacksonPsProcessType,PsThreadType,ExDesktopObjectType, create + duplicate, altitude"1234".cm::callback::register_callback(0x18003D400) →CmRegisterCallbackEx.fltmgrregistration with pre/post callbacks for create, named-pipe create, mailslot create, read, write, query/set info, query/set EA, directory control, FSCTL, lock, cleanup, set security, query-open, acquire-for-section-sync, volume mount/dismount, PnP and KTM transaction notifications.fltmgr::Filter::create_port(0x1800338D0) →FltCreateCommunicationPort("\EspFilterPort").

Two thread callbacks: one for lifecycle, one that runs in the creator’s context.
Thread-start events carry the creator
ps::create_thread_notify_nonsystem is registered as PsCreateThreadNotifyNonSystem. That callback type runs in the context of the thread doing the creating, and WESP takes advantage of it:
- the target:
PsLookupThreadByThreadId(ThreadId)→ new thread + its owning process - the creator:
PsLookupThreadByThreadId(PsGetCurrentThreadId())+IoGetCurrentProcess() ExGetPreviousMode()and a global sequence number (g_EventSequenceCounter)
All four objects go into one ThreadStart event and into RuleEngine::process_event_internal<ThreadStart>. A rule can therefore compare “thread’s process” vs “creator’s process”. That’s the remote-thread / CreateRemoteThread injection signal, but expressed as client rule logic, not hardcoded in the driver.
The fast path is cheap: if no client has a rule for this event type, the callback bails out before building anything:
1
2
3
v8 = *(_QWORD *)(v30[0] + 8);
if ( (*(_DWORD *)(v8 + 196) != 0 || *(_DWORD *)(v8 + 16) != 0) // any subscriber?
&& PsLookupThreadByThreadId(ThreadId, &Thread) >= 0 )
Every sensor callback has this same per-event subscription check at a different offset (e.g. +188 for ObHandleDuplicate, +36 for FileCreate). +196 appears in all of them, so it is most likely a catch-all “subscribed to everything” counter.
If the stack has less than 16 KB left (IoGetStackLimits), the rule engine runs via KeExpandKernelStackAndCalloutEx(…, 0x6000), because the Rust rule evaluation is stack-hungry.



Target thread + creator thread/process in one event: the raw material for remote-thread detection.
What a rule can ask about a thread
ThreadPropertyQuery::query (0x180379490) and ThreadArgument expose:
start_address_mapped_nt_path(0x18034D800): readsETHREAD+0x4E0(the start address on this build), opens the owning process, and callsPsProcessHandle::query_mapped_filename→ which file backs the start address.win32_start_address_mapped_nt_path(0x18034D950): the same for the Win32 start address.- Memory basic info for a thread address property (property kind
9) viaPsProcessHandle::query_memory_basic_info(0x180011A90): region type and protection (image vs private, RWX).
Confirmed field catalogue for a thread argument (ThreadArgument::read_*_property):
| Kind | Id | Field | How it’s read |
|---|---|---|---|
| string | 0 / 1 | StartAddress → backing file (NT path / formatted path) | ETHREAD+0x4E0, query_mapped_filename in owning process |
| string | 2 / 3 | Win32StartAddress → backing file | ZwQueryInformationThread(ThreadQuerySetWin32StartAddress) |
| numeric | 0 | ThreadId | PsGetThreadId |
| numeric | 1 | CreateTime | PsGetThreadCreateTime |
| numeric | 2 | THREAD_BASIC_INFORMATION field |
ZwQueryInformationThread(ThreadBasicInformation) |
| memory | 0 | MEMORY_BASIC_INFORMATION at StartAddress |
ZwQueryVirtualMemory(MemoryBasicInformation) in the owning process |
| memory | 1 | MEMORY_BASIC_INFORMATION at Win32StartAddress |
same |
Which thread? The ThreadStart resolver (resolve_string<ThreadStart>, 0x18010FF70) takes a source selector per field. Selector 3 reads the thread stored at event +0x20, and 4 the thread at +0xA0, i.e. the two thread arguments create_thread_notify_nonsystem builds (new thread and creator thread). Other selectors pull from the process, file stream, volume or a context key. So one rule can say “new thread’s start address is in MEM_PRIVATE + PAGE_EXECUTE_READWRITE and creator process ≠ owning process”.

Start address → backing file: the “shellcode in unbacked memory” check lives here.


The unbacked-memory check: start address → MBI in the target process.
So “thread starts in unbacked RWX/private memory inside another process” is fully expressible as a rule. The field resolver set confirms it: every event type gets resolve_memory_address_basic, resolve_path, resolve_token, resolve_sid, resolve_security_descriptor, and evaluate_at_parent_chain (process ancestry predicates).
Handle access stripping (process/thread/desktop)
ob::pre_ob_operation_callback (0x1800476B0) handles create (Operation == 1) and duplicate (Operation == 2) for process, thread and desktop objects. It builds an ObHandleCreate / ObHandleDuplicate event with:
- target object + type
KernelHandleflag (OperationInformation->Flags & 1)- requested
DesiredAccess - current thread + current process (the opener)
Then it runs process_rules_with_current_thread_process<ObHandleCreate> and, if a rule returned an AccessMaskModification, writes the new mask back:
1
2
3
4
v23 = *(__m128i **)(a2 + 32); // OperationInformation->Parameters
...
if ( (((unsigned __int8)v86 ^ 1) & (v86 != 2)) == 0 )
v23->m128i_i32[0] = v87; // Parameters->CreateHandleInformation.DesiredAccess = modified
A correlation ID is stored in OperationInformation->CallContext (+0x18) so ob::post_ob_operation_callback (0x1800485C0) can match the pre-event to the final granted access.
The persisted rule format (wesp_persistence::layout::v0::modify::EventModify) lists exactly which events are modifiable:
EventModify variant |
Effect |
|---|---|
FoCreate |
rewrite file create DesiredAccess |
QueryOpenFile |
rewrite query-open access |
ObCreateHandle |
rewrite process/thread/desktop handle access |
ObDuplicateHandle |
same, for duplication |
All four carry AccessMaskModification. This is the classic “strip PROCESS_VM_WRITE / PROCESS_VM_OPERATION from handles to a protected process” pattern, made generic and driven by rules.

Rule-driven access stripping on process/thread/desktop handles.
File create access stripping
EspFsFilePreCreate (0x18001D030, IRP_MJ_CREATE pre-op) does the same for files:
1
2
3
4
5
6
7
v57 = Data->Iopb->Parameters.Create.SecurityContext;
if ( v57 != nullptr && (AccessState = v57->AccessState) != nullptr )
{
v57->DesiredAccess = v136; // rule-modified mask
AccessState->RemainingDesiredAccess = v136;
FltSetCallbackDataDirty(Data);
}
It is dispatched through process_rules_with_current_thread_process<FileCreate>, so the opener’s process, thread and token are available to the rule.

File opens can be silently downgraded, e.g. drop write access to a protected path.
The verdict byte: blocking processes, registry and file I/O
The rule engine (RuleEngine::process_event_internal<T>) returns an outcome {matched, action}. Each sensor maps a verdict index 0–4 to an NTSTATUS through a small per-sensor table. Any other index means “no verdict” (5 is also what a failed stack expansion returns).
| Index | Status |
|---|---|
| 0 | 0xC0000906 STATUS_VIRUS_INFECTED |
| 1 | 0xC0000022 STATUS_ACCESS_DENIED |
| 2 | 0xC0000225 STATUS_NOT_FOUND |
| 3 | 0xC0000022 STATUS_ACCESS_DENIED |
| 4 | 0xC0000022 STATUS_ACCESS_DENIED |
The same mapping shows up in three places.
Process creation, in ps::create_process_notify (0x180035280):
1
2
3
4
5
6
if ( (unsigned __int8)v94 < 5u ) {
v75 = g_VerdictToStatus_ProcessCreate[(unsigned __int8)v94];
...
*(_DWORD *)(a3 + 64) = v75; // PS_CREATE_NOTIFY_INFO->CreationStatus -> process creation fails
return;
}

Rule verdict → CreationStatus: WESP can block a process launch.
Registry, in cm::callback::registry_callback (0x18003D4A0). The callback returns the table status, so the operation fails. This applies to RegCreateKey, RegOpenKey, RegDeleteKey, RegSetValueKey, RegDeleteValueKey, RegRenameKey, RegQueryKey, RegQueryValueKey, RegLoadKey and RegSetKeySecurity, each with its own g_VerdictToStatus_Reg* table. The other registry events are notify-only.



10 registry operations return the verdict status, so the operation fails.
File system. All 14 EspFs*Pre* handlers share one table, g_VerdictToFltComplete_FilePreOps (0x180443F20). Each entry is (status << 32) | 1. The C layer (e.g. EspFltPreCreate, 0x18048E104) sees the 1, and the Rust wrapper sets Data->IoStatus.Status and returns FLT_PREOP_COMPLETE. So reads, writes, set-information (rename/delete), set-security, set-EA, FSCTL, lock, cleanup, queries, directory enumeration, query-open, section creation (image mapping) and volume mount can all be failed by a rule.

Verdict index → (status<<32)|1 → the minifilter completes the I/O with that error.
EspFltPreCreate also skips some opens entirely:
- prefetch opens (
GUID_ECP_PREFETCH_OPEN) - CSV down-level opens
- WESP’s own internal opens (
GUID_ESPFLT_ECP_INTERNAL_CREATE)
It also records SMB remote-client info (GUID_ECP_SRV_OPEN) and flags opens that are part of process creation (GUID_ECP_CREATE_USER_PROCESS).



The same verdict fails file I/O at the minifilter.
Image load (ps::load_image_notify) and thread notifications are notify-only. Those kernel callbacks have no way to fail the operation.
How a rule is evaluated
- Re-entrancy guard:
EventDispatcher::enter(0x1802C9F30) FNV-hashes(ThreadId, ThreadCreateTime)into a set. If the current thread is already dispatching, it returns NULL and the nested event is skipped. This keeps WESP from recursing on I/O caused by its own rule evaluation. - Subscription fast path: per-event-type counters (see above). No subscribers means no work.
- Event build: target objects + current thread/process +
ExGetPreviousMode+ sequence number. RuleEngine::process_event_internal<T>: for each client’s ordered rule group:FilterBdd::evaluate(0x180350550) walks the client’s BDD. Leaf predicates:- string ops (
string_match::StringPatternMatcher, lower-cased unless the case flag is set) - numeric / binary compares
RtlEqualSid- SD owner/group
- token groups/privileges
- ECP presence (incl.
FltIsEcpFromUserMode) Collection::contains, i.e. client-managed sets
- string ops (
- Field values are resolved lazily by
EventComparandResolver<T>and cached (field_cache);evaluate_at_parent_chainwalks process ancestry. - On a match:
- apply context-key updates (stateful tags on clients/event objects)
- build the notification (
NotificationBuilder, collecting the process chain, thread and file object) EventQueue::queue_async_notification_internalPostOperationClientMap::insert(to see the post-op result)- set the verdict/modification
- Enforcement: the sensor applies the verdict (status table) or the
AccessMaskModification.


Match → notify → enforce, per client, per event.
BDD wire format (FilterBdd::evaluate):
| Item | Layout |
|---|---|
| root node | bdd[6] |
| node (32 bytes) | +0x00 tag (0 = terminal) · +0x08 predicate index, or the result for a terminal · +0x10 false child · +0x18 true child |
| step | next = node[0x10 + 8 * predicate_result] |
| predicate table | 272-byte entries, 15 predicate kinds; values come from resolver callbacks (a function table passed in by EventComparandResolver<T>) |
| errors | any non-OK resolver result aborts the walk with an error |


The whole detection language reduces to this loop.
Notification budget (AsyncStateInner::enqueue, 0x1803684C0):
- Each queued notification is charged
0x1000 + (payload_regions << 16)bytes against the queue’s limit. - Over the limit → error
25, and the notification is dropped. - Duplicate notification ID →
26; pool failure →33. - Delivery is either direct, or via a worker thread woken by a condvar.

Each notification costs 4 KB + 64 KB per payload region; over budget → dropped.
Who is allowed to drive the engine? Client authentication
Every FilterConnectCommunicationPort lands in fltmgr::connect_callback → ClientManager::handle_connect_request (0x18039E250). Reversed logic:
- Opens
\Registry\Machine\System\Wesp\Policy(KEY_READ). ZwQuerySystemInformation(0x67 = SystemCodeIntegrityInformation)→testsign = CodeIntegrityOptions & 0x2(CODEINTEGRITY_OPTION_TESTSIGN).- Opens the caller’s primary token and walks its security attributes looking for:
- name
WESP://Permission(length0x22) - type
0x10(CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING) - value ≥ 16 bytes, first DWORD =
1(version), second DWORD = permission level
- name
- Decides:
| Condition | Result |
|---|---|
| attribute missing | STATUS_ACCESS_DENIED (0xC0000022) |
level 1 |
allowed as a restricted client, but may not connect as the reserved client ID (first GUID DWORD 0x4D564900) |
level 2 + client GUID whose first DWORD is 0x4D564900 |
ZwQueryInformationProcess(0x3D = ProcessProtectionInformation) must return 0x31 (PPL, signer Antimalware; audit bit masked with 0xF7) |
| any other level | STATUS_INVALID_PARAMETER |
| test-signing enabled | the permission checks are skipped (developer mode) |
Setting token security attributes requires SeTcbPrivilege, so in practice only a TCB-level launcher can mint a WESP client. The top tier also requires being an Antimalware PPL.
Connect request type 5 also checks that the calling process is already in ConnectedClientProcesses::contains_client, and fails with STATUS_ACCESS_DENIED if it isn’t.



WESP clients are authenticated by a token claim + PPL Antimalware, not by a signature on the client.
Boot & ELAM ordering
wesp::elam::elam_sync::wait_for_elam_cm_stop(0x18003D280) is called fromcm::callback::registry_callback(30 call sites). If an ELAM sync is in progress, it blocks onZwWaitForSingleObjectuntil ELAM’s registry phase stops, so WESP never evaluates registry events before ELAM is done.wesp_lib::persistence::loader::PersistedStateLoader::read_clients+BootState::claim_boot_driver_markerload persisted clients and rules (TLV formatwesp_persistence::layout::v0) so protection is active before any user-mode client connects. Awesp_elam_interop::queue::ElamQueuetype also exists, which suggests a queue shared with the ELAM side.ClientRuleCollection::update_rules_persisted(0x1803916B0) can refuse updates withSTATUS_ACCESS_DENIED.- Boot recovery:
BootState::claim_boot_driver_marker(0x180312180) creates a volatileBootMarkerkey;Disposition == REG_CREATED_NEW_KEYmeans “first WESP load this boot”.recovery::BootMonitor::new(0x18037A1C0) subscribes to WNF state0x418B0D3EA3BC0875. When it reads value3, it writesBootId(fromKUSER_SHARED_DATA+0x2C4) to the registry. This is boot-success tracking, so persisted rules that break boot can be detected on the next start.
- Client capability tier: the request dispatcher (
wesp::serverclosure,0x180006640) denies message22(CreateEventQueue) withSTATUS_ACCESS_DENIEDwhenClientObject::capability_tier() == 2. It’s the only tier check in the dispatcher. How tier values map toWESP://Permissionlevels is not proven.

Registry rules are held until the ELAM driver signals CM-stop.


Volatile BootMarker + WNF boot-success tracking for crash-loop recovery.
Full event catalogue (45 types)
| Category | Events |
|---|---|
| Process | ProcessCreate, ProcessTerminate, ProcessLoadImage |
| Thread | ThreadCreate, ThreadStart, ThreadTerminate |
| Object Manager | ObHandleCreate, ObHandleDuplicate |
| Registry | RegCreateKey, RegOpenKey, RegDeleteKey, RegRenameKey, RegEnumKey, RegQueryKey, RegSetValueKey, RegQueryValueKey, RegEnumValueKey, RegDeleteValueKey, RegLoadKey, RegReplaceKey, RegSetKeySecurity, RegSaveKey, RegRestoreKey |
| File | FileCreate, FileOpen, FileQueryOpen, FileRead, FileWrite, FileCleanup, FileQueryInformation, FileSetInformation, FileQueryDirectoryInformation, FileSetSecurity, FileCreateSection, FileFsctl, FileLock, FileUnlock, SetEa |
| KTM | KtmTransactionCommit, KtmTransactionRollback |
| IPC | PipeCreate, MailslotCreate |
| Volume | VolumeMount, VolumeDismount, VolumeFsctl |
Each event type gets its own monomorphised RuleEngine::process_event_internal<T> and its own set of comparand_resolver functions. That’s why the binary has ~930 resolver functions.
Part 2: espclient.dll, the user-mode client
Client architecture

Exports
124 exports, all thin C wrappers (client\dll\api.cpp, client\lib\core.cpp) over Rust (espclient_rs):
| Group | Exports |
|---|---|
| Client lifecycle | EspRegisterClient, EspConnectClient, EspDisconnectClient, EspUnregisterClient, EspEnumerate{Registered,Connected}Clients |
| Rules | EspCreateRule, EspUpdateRules, EspRemoveRulesForClient, EspEnumerateAllRulesForClient |
| Filters | EspCreate{Process,Thread,File,FileObject,FileStream,RegistryKey,Pipe,Mailslot,Token,Volume,Disk,Desktop,KtmTransaction,Event,Client}Filter, EspCreate{And,Or,Xor,Not}Filter |
| Events | EspCreateEventQueue, EspConnectEventQueueWith{Iocp,Callback}, EspArm/Complete/FreeEventNotification |
| State | EspCreate/Update/OpenCollection, EspSetClientContextKey, EspSetEventObjectContextKey |
| Queries | EspQuery*Properties, EspIs*PropertySupported, EspStringMatchesPattern |
Filters are combined into a BDD on the client side (espclient_rs::bdd::RuleBddBuilder::add_filter / serialize_bucket), and string patterns compile to an NFA/trie (string_match::nfa, string_match::trie). The kernel receives a pre-compiled decision diagram, not a scripting language.

The DLL starts the driver for you
Esp::WespDriver::StartIfNeeded (client\lib\service.cpp) runs at the top of EspRegisterClient and EspConnectClient:
1
2
3
4
v1 = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
v4 = OpenServiceW(v1, L"wesp", SERVICE_QUERY_STATUS | SERVICE_START); // 0x14
if ( QueryServiceStatus(v4, &st) && st.dwCurrentState == SERVICE_RUNNING ) -> done
StartServiceW(v4, 0, nullptr); // retried once on error 15631, ERROR_SERVICE_ALREADY_RUNNING (1056) = ok
A static byte caches “already running”, so the SCM round-trip happens once per process.

The driver is a demand-start service named wesp.
Connection context = message type + client GUID
Every connection goes through FilterConnectCommunicationPort. The first DWORD of the connection context tells the driver what you want:
| Type | DLL caller | Context body |
|---|---|---|
1 |
Esp::ClientObject::Register (EspRegisterClient) |
client descriptor (GUID + 2 strings ≤ 256 WCHAR each) |
2 |
Esp::ClientObject::Unregister |
client GUID |
3 |
Esp::ClientObject::Connect (EspConnectClient) |
client GUID (20-byte context) |
4 |
Esp::EventQueue::Connect |
event queue connection |
6 |
Esp::EventQueue::SetStateChangeCallback |
queue state callbacks |
From Esp::ClientObject::Connect:
1
2
3
*(_DWORD *)ctx = 3;
*(__m128i *)(ctx + 4) = *clientGuid;
FilterConnectCommunicationPort(L"\\EspFilterPort", 0, ctx, 20, nullptr, &hPort);
On the driver side, ClientManager::handle_connect_request checks the caller’s token for WESP://Permission. If the client GUID’s first DWORD is 0x4D564900 (a reserved client identity), the caller must also be PPL Antimalware. So the client GUID is not just a label: one specific GUID prefix is tied to the highest trust level.

Connection context {3, ClientGuid}: the kernel checks the GUID against a reserved, PPL-only identity.
Rules are compiled in user mode
EspCreateRule → EspRsCreateRule (0x1800262C0) builds a Rust Rule from the FFI descriptor:
EventConfig::new: which event typeProcessConfig::new/ThreadConfig::new: object scopeContextKeyConfig::new: stateful tags to set on a matchRuleActionMatchSubrules::new: nested sub-rulesproperty_bindings_from_ffi: binding keys, which take a value from one field and use it as a comparand in another, for correlation inside a rulefilter::impl$66::try_from: the filter tree
EspUpdateRules → EspRsSendUpdateRules (0x18002CFC0) then:
rule::config_graph::walk_config_graph<…>: validates every per-event config. There are ~50*Config::try_as_ffitypes:FoCreateConfig,FsFileCreateSectionConfig,ObCreateHandleConfig,ProcessCreateConfig,ImageLoadConfig,RegSetValueKeyConfig,RemoteClientConfig,BootDriverLoadConfig, …binding_keys::BindingMap::insert: resolves bindings.bdd::RuleBddBuilder::add_filter(0x180040480): each comparison becomes a BDD predicate (builders in the table below).RuleBddBuilder::serialize_bucket: sorts and flattens nodes into a bucket.Rule::message_modify: attaches the enforcement action (see the next section).ContextKeyConfig::to_rule_messages: context-key side effects.FltMgrPortHandleBorrow::send_update_rules→FilterSendMessage.
Predicate builders used in step 3:
| Comparison | Builder |
|---|---|
| String / path | StringComparison::to_predicate, to_path_predicate |
| Numeric | NumericComparison::to_predicate |
| Binary | BinaryComparison::to_predicate, serialize_rhs |
| Bool | BoolComparison::to_predicate |
| SID | SidComparison::to_predicate |
| Security descriptor | SecurityDescriptorComparison::to_predicate |
| EA list | EaListComparison::to_predicate |
| Memory region | MemoryAddressBasicComparison::to_predicate |
| Context key | ContextComparison::serialize_predicate |
And/Or/Xor/Not filters (EspCreate{And,Or,Xor,Not}Filter) are merged via bdd::apply::ApplyContext.
The kernel never parses a language. It walks a pre-built decision diagram (FilterBdd::evaluate in wesp.sys).
The enforcement action lives in the rule
espclient_rs::rule::Rule::message_modify (0x180012B20) serialises a rule’s action:
1
2
3
4
5
6
7
switch ( *(_BYTE *)(rule + 9192) ) {
case 0: /* no modification */
case 1:
case 2:
case 3: out = { kind, count = *(u32*)(rule+9216), list = *(u64*)(rule+9208) }; // AccessMaskModificationList
case 4: out = { 4, verdict = *(u8*)(rule+9193) }; // verdict byte
}
This matches the kernel exactly:
- Kinds 1–3 carry
AccessMaskModificationListentries (modify::AccessMaskModificationList::from_ffi). The driver applies them to file create / query-open and to process/thread/desktop handle create/duplicate (EventModify::{FoCreate, QueryOpenFile, ObCreateHandle, ObDuplicateHandle}). - Kind 4 carries a single verdict byte.
wesp.sysmaps index 0–4 toSTATUS_VIRUS_INFECTED/STATUS_ACCESS_DENIED/STATUS_NOT_FOUND/STATUS_ACCESS_DENIED/STATUS_ACCESS_DENIED, and uses it to fail process creation (CreationStatus), 10 registry operations and 14 file pre-operations.

A rule’s action is either “trim these access bits” or “fail with verdict N”.
Event delivery
EspCreateEventQueue / EspOpenEventQueue create a queue in the driver. EspConnectEventQueueWithIocp or EspConnectEventQueueWithCallback → Esp::EventQueue::Connect (context type 4) → Esp::PortListener::Connect:
CreateThreadpool+SetThreadpoolThreadMaximum(nproc)CreateThreadpoolIo(hPort, PortListener::ThreadPoolCallback)PortListener::ArmIo→ overlappedFilterGetMessage
The client then cycles EspAllocateEventNotification → EspArmEventNotification → (callback / IOCP completion) → EspCompleteEventNotification → EspFreeEventNotification. The payload is the driver-built _ESP_EVENT_NOTIFICATION_DATA_V1 buffer, which includes the related-object chain (process ancestry, thread, file object) that the kernel collected at match time.


Events arrive on a thread-pool I/O over the same filter port.
And thanks for reading :)
Hope you enjoyed it
X: @DbgMan
Telegram: @DbgMan