### Enable Provider and Start ETW Trace Listening in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/LobstersExample.md Demonstrates enabling a configured provider for a trace and starting the trace listener. The Start() method blocks, so it's often called on a separate thread for concurrent operations. ```csharp namedTrace.Enable(provider); void startListening() { namedTrace.Start(); } var task = await Task.Factory.StartNew(() => startListening(), TaskCreationOptions.LongRunning); sleep(1000); namedTrace.Stop(); task.Wait(); ``` -------------------------------- ### Enable and Start ETW Traces in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/Threathunters.BlueKrabsetw.Native.ETW/README.md Illustrates how to enable a provider on a specific trace and start the trace. Since the start method is blocking, it is recommended to execute it on a separate thread. ```csharp namedTrace.Enable(powershellProvider); var t = Task.Run(() => namedTrace.Start()); ``` -------------------------------- ### Enable Providers and Start Tracing Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/KrabsExample.md Illustrates how to attach a provider to a trace and start the trace execution. Since start() is a blocking call, it is typically executed on a separate thread. ```cpp namedTrace.enable(powershellProvider); void startListening() { namedTrace.start(); } std::thread t(startListening); sleep(1000); namedTrace.stop(); t.join(); ``` -------------------------------- ### Manage User-Mode ETW Traces with C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Demonstrates how to initialize a user_trace session, configure trace properties, and register event callbacks for specific ETW providers. The example shows how to enable a provider and start the trace on a background thread. ```cpp #include int main() { krabs::user_trace trace(L"MyApplicationTrace"); EVENT_TRACE_PROPERTIES properties = { 0 }; properties.BufferSize = 256; properties.MinimumBuffers = 12; properties.MaximumBuffers = 48; properties.FlushTimer = 1; properties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE; trace.set_trace_properties(&properties); krabs::provider<> powershellProvider(L"{A0C1853B-5C40-4B15-8766-3CF1C58F985A}"); powershellProvider.any(0x10); powershellProvider.all(0x01); powershellProvider.level(5); powershellProvider.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); std::wcout << L"Event: " << schema.event_name() << L" ID: " << schema.event_id() << std::endl; }); trace.enable(powershellProvider); std::thread traceThread([&trace]() { trace.start(); }); std::this_thread::sleep_for(std::chrono::seconds(10)); trace.stop(); traceThread.join(); return 0; } ``` -------------------------------- ### Configure ETW Provider with Filtering in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/LobstersExample.md Shows how to define an ETW Provider using its GUID and set the 'Any' and 'All' bitflags for event filtering. An event callback function is also defined. ```csharp void OnEventRecord(IEventRecord record) {} var trace = new UserTrace(); var provider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); provider.All = 0x10; provider.Any = 0x01; // augment the Any flag. provider.OnEvent += OnEventRecord; ``` -------------------------------- ### Configure ETW Providers in .NET Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Demonstrates how to instantiate and configure ETW providers using GUIDs or names. It covers setting keywords, levels, trace flags for extended data, and enabling rundown events. ```csharp using Microsoft.O365.Security.ETW; using System; // Create provider by GUID var providerByGuid = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); // Create provider by name var providerByName = new Provider("Microsoft-Windows-PowerShell"); // Configure provider settings providerByName.Any = Provider.AllBitsSet; // All keywords providerByName.All = 0; providerByName.Level = 5; // Verbose // Enable extended data collection providerByName.TraceFlags = TraceFlags.IncludeUserSid | TraceFlags.IncludeStackTrace | TraceFlags.IncludeTerminalSessionId; // Enable rundown events providerByName.EnableRundownEvents(); // Subscribe to events providerByName.OnEvent += (IEventRecord record) => { Console.WriteLine($"Event: {record.Name}"); Console.WriteLine($"Task: {record.TaskName}"); Console.WriteLine($"Opcode: {record.OpcodeName}"); Console.WriteLine($"Event ID: {record.Id}"); Console.WriteLine($"Version: {record.Version}"); }; ``` -------------------------------- ### Create and Name UserTrace in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/LobstersExample.md Illustrates how to instantiate a UserTrace object, both with a default name and a custom-specified name. UserTrace represents a stream of ETW events. ```csharp var trace = new UserTrace(); // unnamed trace var namedTrace = new UserTrace("Muffins McGoo"); ``` -------------------------------- ### Configure and Register ETW Provider in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/Threathunters.BlueKrabsetw.Native.ETW/README.md Shows how to define a provider using its GUID, set event filtering flags (Any/All), and attach a callback function to handle incoming events. ```csharp void MyCallbackFunction(EventRecord) {} Provider powershellProvider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); powershellProvider.Any = 0x10; powershellProvider.OnEvent += MyCallbackFunction; ``` -------------------------------- ### Configure ETW Providers and Callbacks Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/KrabsExample.md Shows how to define an ETW provider using its GUID, set filtering flags, and register a callback function to handle incoming events. ```cpp void mycallbackFunction(const EVENT_RECORD &, const trace_context &) {} provider<> powershellProvider(L"{A0C1853B-5C40-4B15-8766-3CF1C58F985A}"); powershellProvider.any(0x10); powershellProvider.any(0x01); // augment the any flag powershellProvider.add_on_event_callback(mycallbackFunction); ``` -------------------------------- ### Configure ETW Provider Settings with krabs C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt The `provider` class in krabs allows configuration of ETW event reception. It can be initialized by GUID or name, and supports setting various flags like keywords, level, and enabling stack traces or rundown events. Callbacks can be added for event handling and error reporting. ```cpp #include // Create provider by GUID krabs::provider<> providerByGuid(L"{A0C1853B-5C40-4B15-8766-3CF1C58F985A}"); // Create provider by name (resolves GUID automatically) krabs::provider<> providerByName(L"Microsoft-Windows-PowerShell"); // Configure provider flags providerByName.any(0xFFFFFFFF); // Match any of these keywords providerByName.all(0x00); // Match all of these keywords providerByName.level(5); // Verbose level providerByName.enable_property(EVENT_ENABLE_PROPERTY_STACK_TRACE); // Enable stack traces // Enable rundown events (capture current state on start) providerByName.enable_rundown_events(); // Add event callback using lambda providerByName.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); std::wcout << L"Provider: " << schema.provider_name() << std::endl; std::wcout << L"Event: " << schema.event_name() << std::endl; std::wcout << L"Task: " << schema.task_name() << std::endl; std::wcout << L"Opcode: " << schema.opcode_name() << std::endl; }); // Add error callback for handling schema lookup failures providerByName.add_on_error_callback([](const EVENT_RECORD& record, const std::string& errorMessage) { std::cerr << "Error processing event: " << errorMessage << std::endl; }); ``` -------------------------------- ### Initialize UserTrace in C# Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/Threathunters.BlueKrabsetw.Native.ETW/README.md Demonstrates how to instantiate a UserTrace object. Traces can be created with an arbitrary name or left unnamed for default handling. ```csharp UserTrace trace = new UserTrace(); // unnamed trace UserTrace namedTrace = new UserTrace("Muffins McGoo"); ``` -------------------------------- ### Initialize User Traces with BlueKrab Source: https://github.com/threathunters-io/bluekrabsetw/blob/master/docs/KrabsExample.md Demonstrates how to instantiate a user_trace object in C++. Traces can be created with an arbitrary name or left unnamed for automatic naming. ```cpp user_trace trace(); // unnamed trace user_trace namedTrace(L"Muffins McGoo"); ``` -------------------------------- ### Manage User-Mode ETW Traces in .NET Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Shows how to initialize a UserTrace in C#, configure trace properties, and start/stop the tracing process on a background thread. It includes error handling and event subscription via the Microsoft.O365.Security.ETW namespace. ```csharp using Microsoft.O365.Security.ETW; using System; using System.Threading; using System.Threading.Tasks; class Program { static void Main() { // Create named trace using (var trace = new UserTrace("MyManagedTrace")) { // Configure trace properties (optional) var properties = new EventTraceProperties { BufferSize = 256, MinimumBuffers = 12, MaximumBuffers = 48, FlushTimer = 1, LogFileMode = (uint)LogFileModeFlags.FLAG_EVENT_TRACE_REAL_TIME_MODE }; trace.SetTraceProperties(properties); // Create provider var provider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); // Configure provider provider.Any = 0xFFFFFFFF; provider.Level = 5; provider.TraceFlags = TraceFlags.IncludeStackTrace; // Subscribe to events provider.OnEvent += (IEventRecord record) => { Console.WriteLine($"Event: {record.Name}"); Console.WriteLine($"Provider: {record.ProviderName}"); Console.WriteLine($"Process ID: {record.ProcessId}"); Console.WriteLine($"Thread ID: {record.ThreadId}"); Console.WriteLine($"Timestamp: {record.Timestamp}"); }; // Handle errors provider.OnError += (EventRecordError error) => { Console.WriteLine($"Error: {error.Message}"); }; // Enable provider trace.Enable(provider); // Start trace on background thread var cts = new CancellationTokenSource(); var traceTask = Task.Factory.StartNew(() => trace.Start(), TaskCreationOptions.LongRunning); // Run for 30 seconds Thread.Sleep(30000); // Stop trace trace.Stop(); traceTask.Wait(); } } } ``` -------------------------------- ### Capture Kernel-Mode Tracing in C# Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Illustrates how to access kernel-level events using KernelTrace. This requires administrative privileges and demonstrates tracking process creation and image loading events. ```csharp using (var trace = new KernelTrace("MyKernelTrace")) { var processProvider = new KernelProvider(KernelProvider.PROCESS_PROVIDER, KernelProvider.PROCESS_GUID); var imageLoadProvider = new KernelProvider(KernelProvider.IMAGE_LOAD_PROVIDER, KernelProvider.IMAGE_LOAD_GUID); processProvider.OnEvent += (IEventRecord record) => { if (record.Opcode == 1) { Console.WriteLine($"Process: {record.GetUnicodeString("ImageFileName")}"); Console.WriteLine($"PID: {record.GetUInt32("ProcessId")}"); Console.WriteLine($"PPID: {record.GetUInt32("ParentId")}"); } }; imageLoadProvider.OnEvent += (IEventRecord record) => { Console.WriteLine($"Image Loaded: {record.GetUnicodeString("FileName")}"); Console.WriteLine($"Base Address: 0x{record.GetUInt64("ImageBase"):X}"); }; trace.Enable(processProvider); trace.Enable(imageLoadProvider); trace.Start(); } ``` -------------------------------- ### Manage Kernel-Mode ETW Traces with C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Illustrates the use of the kernel_trace class to capture system-level events such as process creation and network activity. Requires administrative privileges to execute successfully. ```cpp #include int main() { krabs::kernel_trace trace(L"MyKernelTrace"); krabs::kernel::process_provider processProvider; krabs::kernel::image_load_provider imageLoadProvider; krabs::kernel::network_tcpip_provider networkProvider; processProvider.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); krabs::parser parser(schema); if (schema.event_opcode() == 1) { auto processId = parser.parse(L"ProcessId"); auto imageName = parser.parse(L"ImageFileName"); std::wcout << L"Process Started: " << imageName << L" (PID: " << processId << L")" << std::endl; } }); trace.enable(processProvider); trace.enable(imageLoadProvider); trace.enable(networkProvider); std::thread traceThread([&trace]() { trace.start(); }); std::this_thread::sleep_for(std::chrono::seconds(30)); trace.stop(); traceThread.join(); return 0; } ``` -------------------------------- ### Query Trace Statistics in C# Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt This snippet demonstrates how to query and display statistics for an active ETW trace session using the bluekrabsetw library in C#. It shows how to access total events, handled events, lost events, and buffer information. It also includes a check for event loss and calculates the percentage of lost events. ```csharp using Microsoft.O365.Security.ETW; using System; var trace = new UserTrace(); // ... configure and start trace ... // Query statistics TraceStats stats = trace.QueryStats(); Console.WriteLine($"Events Total: {stats.EventsTotal}"); Console.WriteLine($"Events Handled: {stats.EventsHandled}"); Console.WriteLine($"Events Lost: {stats.EventsLost}"); Console.WriteLine($"Buffers: {stats.BuffersCount}"); Console.WriteLine($"Buffers Free: {stats.BuffersFree}"); Console.WriteLine($"Buffer Size: {stats.BufferSize} KB"); // Monitor for event loss if (stats.EventsLost > 0) { double lossPercent = (double)stats.EventsLost / stats.EventsTotal * 100; Console.WriteLine($"WARNING: {lossPercent:F2}% event loss detected!"); } ``` -------------------------------- ### Manage ETW Providers Dynamically in C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Shows how to enable and disable ETW providers at runtime while a trace session is active. This allows for flexible monitoring without needing to restart the entire trace. ```cpp #include int main() { krabs::user_trace trace(L"DynamicTrace"); krabs::provider<> provider1(L"Microsoft-Windows-PowerShell"); krabs::provider<> provider2(L"Microsoft-Windows-DNS-Client"); provider1.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { std::wcout << L"PowerShell event" << std::endl; }); provider2.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { std::wcout << L"DNS event" << std::endl; }); trace.enable(provider1); std::thread traceThread([&trace]() { trace.start(); }); std::this_thread::sleep_for(std::chrono::seconds(5)); trace.enable(provider2); std::wcout << L"DNS provider enabled" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); trace.disable(provider1); std::wcout << L"PowerShell provider disabled" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(10)); trace.stop(); traceThread.join(); return 0; } ``` -------------------------------- ### Process ETL Trace Files with C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Demonstrates how to use the krabs library to read and process events from a saved .etl file. It configures a user_trace, attaches a provider, and defines a callback to output event names and timestamps. ```cpp #include int main() { krabs::user_trace trace; // Set trace to read from file trace.set_trace_filename(L"C:\\Logs\\trace.etl"); // Create provider for events in the file krabs::provider<> provider(L"{A0C1853B-5C40-4B15-8766-3CF1C58F985A}"); provider.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); std::wcout << L"[" << schema.timestamp().QuadPart << L"] " << schema.event_name() << std::endl; }); trace.enable(provider); // Open and process the file trace.open(); trace.process(); // Processes all events, then returns std::wcout << L"Processed " << trace.buffers_processed() << L" buffers" << std::endl; return 0; } ``` -------------------------------- ### Query Trace Statistics in C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Provides a function to retrieve and display runtime statistics for an ETW trace session, including event counts, buffer utilization, and loss rates. ```cpp #include void monitor_trace_health(krabs::user_trace& trace) { krabs::trace_stats stats = trace.query_stats(); std::wcout << L"=== Trace Statistics ===" << std::endl; std::wcout << L"Events Total: " << stats.events_total << std::endl; std::wcout << L"Events Handled: " << stats.events_handled << std::endl; std::wcout << L"Events Lost: " << stats.events_lost << std::endl; std::wcout << L"Buffers Count: " << stats.buffers_count << std::endl; std::wcout << L"Buffers Free: " << stats.buffers_free << std::endl; std::wcout << L"Buffers Written: " << stats.buffers_written << std::endl; std::wcout << L"Buffers Lost: " << stats.buffers_lost << std::endl; std::wcout << L"Buffer Size (KB): " << stats.buffer_size << std::endl; std::wcout << L"Logger Name: " << stats.logger_name << std::endl; if (stats.events_total > 0) { double lossRate = (double)stats.events_lost / stats.events_total * 100.0; std::wcout << L"Loss Rate: " << lossRate << L"%" << std::endl; } } ``` -------------------------------- ### Parse Event Data with IEventRecord in C# Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Demonstrates how to extract various data types from an IEventRecord, including strings, integers, network addresses, and stack traces. It also shows how to iterate through all available properties within an event. ```csharp provider.OnEvent += (IEventRecord record) => { string commandLine = record.GetUnicodeString("CommandLine"); string ansiString = record.GetAnsiString("FileName"); string countedString = record.GetCountedString("Message"); string optional = record.GetUnicodeString("OptionalField", "default"); if (record.TryGetUnicodeString("MaybeExists", out string result)) { Console.WriteLine($"Found: {result}"); } int int32Value = record.GetInt32("ReturnCode"); uint uint32Value = record.GetUInt32("ProcessId"); long int64Value = record.GetInt64("FileSize"); ulong uint64Value = record.GetUInt64("Address"); byte byteValue = record.GetUInt8("Flags"); IPAddress ipAddress = record.GetIPAddress("RemoteAddress"); SocketAddress socketAddress = record.GetSocketAddress("LocalEndpoint"); DateTime timestamp = record.GetDateTime("CreationTime"); byte[] rawData = record.GetBinary("Payload"); var stackTrace = record.GetStackTrace(); foreach (var address in stackTrace) { Console.WriteLine($" 0x{address:X}"); } foreach (var property in record.Properties) { Console.WriteLine($"Property: {property.Name}"); } }; ``` -------------------------------- ### Filter Events with EventFilter in C# Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Shows how to reduce processing overhead by filtering events based on specific IDs or custom predicates. Filters are registered to a provider before the trace is enabled. ```csharp var trace = new UserTrace(); var provider = new Provider(Guid.Parse("{...}")); var processStartFilter = new EventFilter(1); processStartFilter.OnEvent += (IEventRecord record) => { Console.WriteLine($"Process Start: {record.GetUnicodeString("ImageName")}"); }; var multiFilter = new EventFilter(new ushort[] { 1, 2, 3 }); multiFilter.OnEvent += (IEventRecord record) => { Console.WriteLine($"Event ID: {record.Id}"); }; var customFilter = new EventFilter((record, context) => { return record.ProcessId > 1000; }); customFilter.OnEvent += (IEventRecord record) => { Console.WriteLine($"Filtered event from PID: {record.ProcessId}"); }; provider.AddFilter(processStartFilter); provider.AddFilter(customFilter); trace.Enable(provider); ``` -------------------------------- ### Filter ETW Events with event_filter in C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt Demonstrates how to use the event_filter class to selectively process ETW events based on IDs or custom predicates. This helps reduce overhead by ignoring irrelevant events before they reach the callback logic. ```cpp #include int main() { krabs::user_trace trace; krabs::provider<> provider(L"Microsoft-Windows-Kernel-Process"); provider.any(0x10); krabs::event_filter processStartFilter(1); processStartFilter.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); krabs::parser parser(schema); std::wcout << L"Process started: " << parser.parse(L"ImageName") << std::endl; }); krabs::event_filter multiEventFilter({1, 2, 3}); multiEventFilter.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); std::wcout << L"Event ID: " << schema.event_id() << std::endl; }); krabs::event_filter customFilter([](const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); krabs::parser parser(schema); auto processId = parser.parse(L"ProcessId"); return processId > 1000; }); customFilter.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& context) { std::wcout << L"Filtered event received" << std::endl; }); provider.add_filter(processStartFilter); provider.add_filter(customFilter); trace.enable(provider); std::thread t([&trace]() { trace.start(); }); std::this_thread::sleep_for(std::chrono::seconds(30)); trace.stop(); t.join(); return 0; } ``` -------------------------------- ### Parse ETW Event Properties with krabs C++ Source: https://context7.com/threathunters-io/bluekrabsetw/llms.txt The `parser` class in krabs is used to extract strongly-typed property values from ETW events based on the event schema. It supports parsing various data types including strings, integers, IP addresses, SIDs, binary data, and pointers. Safe parsing is available via `try_parse`, and all properties can be iterated. ```cpp #include void on_event(const EVENT_RECORD& record, const krabs::trace_context& context) { krabs::schema schema(record, context.schema_locator); krabs::parser parser(schema); // Parse various data types auto stringValue = parser.parse(L"CommandLine"); auto ansiString = parser.parse(L"FileName"); auto uint32Value = parser.parse(L"ProcessId"); auto uint64Value = parser.parse(L"Address"); auto int32Value = parser.parse(L"ReturnCode"); auto boolValue = parser.parse(L"Success"); // Parse IP addresses (IPv4/IPv6) auto ipAddress = parser.parse(L"RemoteAddress"); std::wcout << L"IP: " << ipAddress.to_string() << std::endl; // Parse socket addresses auto socketAddr = parser.parse(L"LocalAddress"); // Parse SID (Security Identifier) auto sid = parser.parse(L"UserSid"); std::wcout << L"SID: " << sid.to_string() << std::endl; // Parse binary data auto binaryData = parser.parse(L"RawData"); // Parse pointers (handles 32/64-bit) auto pointer = parser.parse(L"ObjectPointer"); // Safe parsing with try_parse (returns false on failure) std::wstring optionalValue; if (parser.try_parse(L"OptionalProperty", optionalValue)) { std::wcout << L"Optional: " << optionalValue << std::endl; } // Iterate all properties for (auto& property : parser.properties()) { std::wcout << L"Property: " << property.name() << std::endl; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.