Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
event_queue.h File Reference
#include <ntddk.h>
#include "pano_events.h"

Go to the source code of this file.

Macros

#define PANO_MAX_QUEUED_EVENTS   2048
 Maximum number of events buffered while no GET_EVENT request is pending. Older buffered events are not discarded; new events are dropped once the FIFO is full.

Functions

NTSTATUS EventQueueInit ()
 Initializes the event queue. Call once from DriverEntry before any producer can run and before the device is exposed.
void EventQueueCleanup ()
 Cancels every pending GET_EVENT request and frees all buffered events. Call from the unload path after all producers have been stopped.
BOOLEAN EventQueueReceiveRequest (PIRP Irp, NTSTATUS *Status)
 Queues a GET_EVENT request. Call from the IOCTL dispatch routine. On success the IRP is either completed immediately (an event was waiting) or marked pending and parked in the cancel-safe queue; in both cases the dispatch routine must return the value written to *Status and must not touch the IRP again.
BOOLEAN EventQueueIsConsumerProcess (UINT64 ProcessId)
 Checks whether a process is the one reading events (the service). The filter does not report that process's own file activity: its log writes, database and scans would otherwise each produce more events for it to read, and it discards them anyway. Tracks the process of the handle that most recently became a consumer. Safe at any IRQL <= DISPATCH_LEVEL.
void EventQueueCleanupFile (PFILE_OBJECT FileObject)
 Handles IRP_MJ_CLEANUP for a handle to the device: cancels the GET_EVENT requests still parked for it and, if it was the last consumer, drops the buffered events. Call from the IRP_MJ_CLEANUP dispatch routine.
NTSTATUS PanoReportEvent (PANO_EVENT_TYPE Type, _In_reads_bytes_(PayloadSize) const void *Payload, UINT32 PayloadSize)
 Reports one event. Delivers it to a pending GET_EVENT request if one is waiting, otherwise buffers it. Safe to call at IRQL <= DISPATCH_LEVEL.
NTSTATUS PanoReportFileEvent (PANO_EVENT_TYPE Type, UINT64 ProcessId, UINT64 ThreadId, INT64 FileOffset, UINT32 Length, UINT32 Flags, _In_reads_opt_(NameLength) const WCHAR *FileName, UINT32 NameLength)
 Convenience wrapper that builds a PANO_FILE_EVENT_DATA event. FileName is copied and truncated to PANO_MAX_FILE_NAME_LENGTH (PANO_FLAG_NAME_TRUNCATED is set in Flags when truncation occurs). Pass NameLength in WCHARs.
NTSTATUS PanoReportFileModifiedEvent (UINT64 ProcessId, UINT64 ThreadId, UINT64 Writes, UINT64 Bytes, INT64 FirstWriteTime, UINT32 Flags, _In_reads_opt_(NameLength) const WCHAR *FileName, UINT32 NameLength)
 Convenience wrapper that builds a PANO_EVENT_FILE_MODIFIED event. FileName is copied and truncated to PANO_MAX_MODIFIED_FILE_NAME_LENGTH (PANO_FLAG_NAME_TRUNCATED is set when truncation occurs). Pass NameLength in WCHARs.
NTSTATUS PanoReportRenameEvent (UINT64 ProcessId, UINT64 ThreadId, UINT32 Flags, _In_reads_opt_(SourceNameLength) const WCHAR *SourceName, UINT32 SourceNameLength, _In_reads_opt_(DestinationNameLength) const WCHAR *DestinationName, UINT32 DestinationNameLength)
 Convenience wrapper that builds a PANO_RENAME_EVENT_DATA event. If the two names together exceed PANO_MAX_RENAME_NAMES_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED is set. Pass lengths in WCHARs.
NTSTATUS PanoReportRegistryEvent (PANO_EVENT_TYPE Type, UINT64 ProcessId, UINT64 ThreadId, UINT32 Flags, UINT32 Detail, UINT32 DataSize, _In_reads_opt_(KeyNameLength) const WCHAR *KeyName, UINT32 KeyNameLength, _In_reads_opt_(SecondNameLength) const WCHAR *SecondName, UINT32 SecondNameLength, _In_reads_bytes_opt_(DataLength) const void *Data, UINT32 DataLength)
 Convenience wrapper that builds a PANO_REGISTRY_EVENT_DATA event. Every buffer must be kernel memory: the caller captures anything from user mode first. Data is cut to PANO_MAX_REGISTRY_DATA_SIZE bytes (PANO_FLAG_DATA_TRUNCATED is set). If the two names together exceed PANO_MAX_REGISTRY_NAMES_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED is set. Pass name lengths in WCHARs and DataLength in bytes.
NTSTATUS PanoReportProcessEvent (PANO_EVENT_TYPE Type, UINT64 ProcessId, UINT64 ParentProcessId, UINT64 CreatingProcessId, UINT64 CreatingThreadId, _In_reads_opt_(ImageNameLength) const WCHAR *ImageName, UINT32 ImageNameLength, _In_reads_opt_(CommandLineLength) const WCHAR *CommandLine, UINT32 CommandLineLength)
 Convenience wrapper that builds a PANO_PROCESS_EVENT_DATA event. If the image name and command line together exceed PANO_MAX_PROCESS_STRINGS_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED / PANO_FLAG_COMMAND_LINE_TRUNCATED are set for whichever was cut. Pass lengths in WCHARs.

Macro Definition Documentation

◆ PANO_MAX_QUEUED_EVENTS

#define PANO_MAX_QUEUED_EVENTS   2048

Maximum number of events buffered while no GET_EVENT request is pending. Older buffered events are not discarded; new events are dropped once the FIFO is full.

Definition at line 25 of file event_queue.h.

Function Documentation

◆ EventQueueCleanup()

void EventQueueCleanup ( )

Cancels every pending GET_EVENT request and frees all buffered events. Call from the unload path after all producers have been stopped.

Definition at line 202 of file event_queue.cpp.

203{
204 // Cancel every parked request.
205 PIRP irp;
206 while ((irp = IoCsqRemoveNextIrp(&g_Csq, NULL)) != NULL) {
207 irp->IoStatus.Status = STATUS_CANCELLED;
208 irp->IoStatus.Information = 0;
209 IoCompleteRequest(irp, IO_NO_INCREMENT);
210 }
211
212 // Drop every buffered event.
213 PPANO_EVENT_NODE node;
214 while ((node = DequeueEvent()) != NULL) {
215 ExFreePoolWithTag(node, PANO_EVENT_POOL_TAG);
216 }
217}
struct _PANO_EVENT_NODE * PPANO_EVENT_NODE
#define PANO_EVENT_POOL_TAG

References PANO_EVENT_POOL_TAG.

Referenced by DriverEntry(), and UnloadPanoptes().

◆ EventQueueCleanupFile()

void EventQueueCleanupFile ( PFILE_OBJECT FileObject)

Handles IRP_MJ_CLEANUP for a handle to the device: cancels the GET_EVENT requests still parked for it and, if it was the last consumer, drops the buffered events. Call from the IRP_MJ_CLEANUP dispatch routine.

Parameters
FileObjectThe file object being cleaned up.

Definition at line 277 of file event_queue.cpp.

278{
279 // Complete the requests this handle still has parked. A process that is exiting
280 // has had them cancelled already, but one that just closes its handle has not
281 PIRP irp;
282 while ((irp = IoCsqRemoveNextIrp(&g_Csq, FileObject)) != NULL) {
283 irp->IoStatus.Status = STATUS_CANCELLED;
284 irp->IoStatus.Information = 0;
285 IoCompleteRequest(irp, IO_NO_INCREMENT);
286 }
287
288 // Called for both IRP_MJ_CLEANUP and IRP_MJ_CLOSE; only the first unmarks the
289 // handle. IRP_MJ_CLOSE covers a GET_EVENT request that was still being
290 // dispatched when IRP_MJ_CLEANUP arrived and marked the handle afterwards
291 if (InterlockedCompareExchangePointer(&FileObject->FsContext, NULL, PANO_CONSUMER_MARK) != PANO_CONSUMER_MARK) {
292 return;
293 }
294
295 // Stop exempting this handle's process, unless a newer consumer has replaced it
296 InterlockedCompareExchange64(&g_ConsumerProcessId, 0, (LONG64)(ULONG_PTR)FileObject->FsContext2);
297 FileObject->FsContext2 = NULL;
298
299 if (InterlockedDecrement(&g_Consumers) != 0) {
300 return;
301 }
302
303 // No consumer is left. What is buffered would only reach the next service as
304 // stale events, so it is dropped and counted
305 KIRQL irql;
306 LIST_ENTRY dropped;
307 InitializeListHead(&dropped);
308 LONG count = 0;
309
310 KeAcquireSpinLock(&g_EventLock, &irql);
311 while (!IsListEmpty(&g_EventList)) {
312 InsertTailList(&dropped, RemoveHeadList(&g_EventList));
313 count++;
314 }
315 g_EventCount = 0;
316 KeReleaseSpinLock(&g_EventLock, irql);
317
318 while (!IsListEmpty(&dropped)) {
319 PPANO_EVENT_NODE node = CONTAINING_RECORD(RemoveHeadList(&dropped), PANO_EVENT_NODE, ListEntry);
320 ExFreePoolWithTag(node, PANO_EVENT_POOL_TAG);
321 }
322 InterlockedAdd(&g_DroppedNoConsumer, count);
323}
struct _PANO_EVENT_NODE PANO_EVENT_NODE
#define PANO_CONSUMER_MARK

References PANO_CONSUMER_MARK, and PANO_EVENT_POOL_TAG.

◆ EventQueueInit()

NTSTATUS EventQueueInit ( )

Initializes the event queue. Call once from DriverEntry before any producer can run and before the device is exposed.

Definition at line 181 of file event_queue.cpp.

182{
183 InitializeListHead(&g_IrpList);
184 InitializeListHead(&g_EventList);
185 KeInitializeSpinLock(&g_IrpLock);
186 KeInitializeSpinLock(&g_EventLock);
187 g_EventCount = 0;
188 g_Dropped = 0;
189 g_Consumers = 0;
190 g_DroppedNoConsumer = 0;
191
192 return IoCsqInitialize(
193 &g_Csq,
194 CsqInsertIrp,
195 CsqRemoveIrp,
196 CsqPeekNextIrp,
197 CsqAcquireLock,
198 CsqReleaseLock,
199 CsqCompleteCanceledIrp);
200}

Referenced by DriverEntry().

◆ EventQueueIsConsumerProcess()

BOOLEAN EventQueueIsConsumerProcess ( UINT64 ProcessId)

Checks whether a process is the one reading events (the service). The filter does not report that process's own file activity: its log writes, database and scans would otherwise each produce more events for it to read, and it discards them anyway. Tracks the process of the handle that most recently became a consumer. Safe at any IRQL <= DISPATCH_LEVEL.

Definition at line 270 of file event_queue.cpp.

271{
272 // An aligned 64-bit read is atomic on x64
273 LONG64 consumer = g_ConsumerProcessId;
274 return consumer != 0 && (UINT64)consumer == ProcessId;
275}

◆ EventQueueReceiveRequest()

BOOLEAN EventQueueReceiveRequest ( PIRP Irp,
NTSTATUS * Status )

Queues a GET_EVENT request. Call from the IOCTL dispatch routine. On success the IRP is either completed immediately (an event was waiting) or marked pending and parked in the cancel-safe queue; in both cases the dispatch routine must return the value written to *Status and must not touch the IRP again.

Parameters
IrpThe IOCTL_PANOPTES_GET_EVENT request (METHOD_BUFFERED).
StatusReceives the status the dispatch routine should return.
Returns
TRUE if the queue took ownership of the IRP, FALSE if the caller must complete it with *Status (e.g. the output buffer was too small).

Definition at line 219 of file event_queue.cpp.

220{
221 PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp);
222
223 // Every buffered event is <= PANO_MAX_EVENT_SIZE, so a request that can hold
224 // that much can hold any event and the copy at delivery never truncates.
225 if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < PANO_MAX_EVENT_SIZE) {
226 *Status = STATUS_BUFFER_TOO_SMALL;
227 return FALSE;
228 }
229
230 // The handle's first request makes it a consumer, and events start being kept
231 if (InterlockedCompareExchangePointer(&irpSp->FileObject->FsContext, PANO_CONSUMER_MARK, NULL) == NULL) {
232 // The device has no drivers above it, so the request is dispatched in the context of
233 // the thread that sent it
234 LONG64 processId = (LONG64)(ULONG_PTR)PsGetCurrentProcessId();
235 irpSp->FileObject->FsContext2 = (PVOID)(ULONG_PTR)processId;
236 InterlockedExchange64(&g_ConsumerProcessId, processId);
237 InterlockedIncrement(&g_Consumers);
238 }
239
240 // Fast path: an event is already waiting.
241 PPANO_EVENT_NODE node = DequeueEvent();
242 if (node != NULL) {
243 DeliverEventToIrp(Irp, node);
244 *Status = STATUS_SUCCESS;
245 return TRUE;
246 }
247
248 // Park the request. IoCsqInsertIrp marks it pending for us.
249 IoCsqInsertIrp(&g_Csq, Irp, NULL);
250
251 // An event may have been buffered after our DequeueEvent and before the
252 // insert, while no request was parked to receive it. Drain it now so the
253 // request does not stall behind an event that already arrived.
254 node = DequeueEvent();
255 if (node != NULL) {
256 PIRP waiter = IoCsqRemoveNextIrp(&g_Csq, NULL);
257 if (waiter != NULL) {
258 DeliverEventToIrp(waiter, node);
259 }
260 else {
261 // Our request was already taken (by a producer); put the event back.
262 RequeueEventFront(node);
263 }
264 }
265
266 *Status = STATUS_PENDING;
267 return TRUE;
268}
#define PANO_MAX_EVENT_SIZE
The output buffer size the service passes with IOCTL_PANOPTES_GET_EVENT. The driver never returns an ...
Definition pano_events.h:59

References PANO_CONSUMER_MARK, and PANO_MAX_EVENT_SIZE.

◆ PanoReportEvent()

NTSTATUS PanoReportEvent ( PANO_EVENT_TYPE Type,
_In_reads_bytes_(PayloadSize) const void * Payload,
UINT32 PayloadSize )

Reports one event. Delivers it to a pending GET_EVENT request if one is waiting, otherwise buffers it. Safe to call at IRQL <= DISPATCH_LEVEL.

Parameters
TypeA PANO_EVENT_TYPE.
PayloadThe event body that follows the header (e.g. a PANO_FILE_EVENT_DATA).
PayloadSizeSize of Payload in bytes.
Returns
STATUS_SUCCESS if delivered or buffered, STATUS_INSUFFICIENT_RESOURCES if the event could not be allocated, STATUS_BUFFER_OVERFLOW if the event is too large.

◆ PanoReportFileEvent()

NTSTATUS PanoReportFileEvent ( PANO_EVENT_TYPE Type,
UINT64 ProcessId,
UINT64 ThreadId,
INT64 FileOffset,
UINT32 Length,
UINT32 Flags,
_In_reads_opt_(NameLength) const WCHAR * FileName,
UINT32 NameLength )

Convenience wrapper that builds a PANO_FILE_EVENT_DATA event. FileName is copied and truncated to PANO_MAX_FILE_NAME_LENGTH (PANO_FLAG_NAME_TRUNCATED is set in Flags when truncation occurs). Pass NameLength in WCHARs.

◆ PanoReportFileModifiedEvent()

NTSTATUS PanoReportFileModifiedEvent ( UINT64 ProcessId,
UINT64 ThreadId,
UINT64 Writes,
UINT64 Bytes,
INT64 FirstWriteTime,
UINT32 Flags,
_In_reads_opt_(NameLength) const WCHAR * FileName,
UINT32 NameLength )

Convenience wrapper that builds a PANO_EVENT_FILE_MODIFIED event. FileName is copied and truncated to PANO_MAX_MODIFIED_FILE_NAME_LENGTH (PANO_FLAG_NAME_TRUNCATED is set when truncation occurs). Pass NameLength in WCHARs.

◆ PanoReportProcessEvent()

NTSTATUS PanoReportProcessEvent ( PANO_EVENT_TYPE Type,
UINT64 ProcessId,
UINT64 ParentProcessId,
UINT64 CreatingProcessId,
UINT64 CreatingThreadId,
_In_reads_opt_(ImageNameLength) const WCHAR * ImageName,
UINT32 ImageNameLength,
_In_reads_opt_(CommandLineLength) const WCHAR * CommandLine,
UINT32 CommandLineLength )

Convenience wrapper that builds a PANO_PROCESS_EVENT_DATA event. If the image name and command line together exceed PANO_MAX_PROCESS_STRINGS_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED / PANO_FLAG_COMMAND_LINE_TRUNCATED are set for whichever was cut. Pass lengths in WCHARs.

Referenced by ProcessCreateCallback().

◆ PanoReportRegistryEvent()

NTSTATUS PanoReportRegistryEvent ( PANO_EVENT_TYPE Type,
UINT64 ProcessId,
UINT64 ThreadId,
UINT32 Flags,
UINT32 Detail,
UINT32 DataSize,
_In_reads_opt_(KeyNameLength) const WCHAR * KeyName,
UINT32 KeyNameLength,
_In_reads_opt_(SecondNameLength) const WCHAR * SecondName,
UINT32 SecondNameLength,
_In_reads_bytes_opt_(DataLength) const void * Data,
UINT32 DataLength )

Convenience wrapper that builds a PANO_REGISTRY_EVENT_DATA event. Every buffer must be kernel memory: the caller captures anything from user mode first. Data is cut to PANO_MAX_REGISTRY_DATA_SIZE bytes (PANO_FLAG_DATA_TRUNCATED is set). If the two names together exceed PANO_MAX_REGISTRY_NAMES_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED is set. Pass name lengths in WCHARs and DataLength in bytes.

◆ PanoReportRenameEvent()

NTSTATUS PanoReportRenameEvent ( UINT64 ProcessId,
UINT64 ThreadId,
UINT32 Flags,
_In_reads_opt_(SourceNameLength) const WCHAR * SourceName,
UINT32 SourceNameLength,
_In_reads_opt_(DestinationNameLength) const WCHAR * DestinationName,
UINT32 DestinationNameLength )

Convenience wrapper that builds a PANO_RENAME_EVENT_DATA event. If the two names together exceed PANO_MAX_RENAME_NAMES_LENGTH they are truncated (the longer one first) and PANO_FLAG_NAME_TRUNCATED is set. Pass lengths in WCHARs.

Referenced by PostSetInformationCallback().