public static void Start() { var trace = new UserTrace("UserTrace006_Rundown"); // Rundown events are not true real-time tracing events. Instead they describe the state of the system. // Usually these are just extra events in the provider. For example, Microsoft-Windows-Kernel-Process // has ProcessRundown events as well as ProcessStart events. var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.Any = 0x10; // WINEVENT_KEYWORD_PROCESS // ...but the rundown events often cannot be enabled by keyword alone. // The trace needs to be sent EVENT_CONTROL_CODE_CAPTURE_STATE. // This is what EnableRundownEvents() does. provider.EnableRundownEvents(); // real-time process start events var processFilter = new EventFilter(Filter.EventIdIs(1)); // ProcessStart processFilter.OnEvent += ProcessEventHandler; provider.AddFilter(processFilter); // process rundown events - i.e. running processes var processRundownFilter = new EventFilter(Filter.EventIdIs(15)); // ProcessRundown processRundownFilter.OnEvent += ProcessEventHandler; provider.AddFilter(processRundownFilter); trace.Enable(provider); trace.Start(); }
private PSEtwUserProvider CreateWmiActivityProvider() { const int WMIEventId = 11; const string providerName = "Microsoft-Windows-WMI-Activity"; var wmiProvider = new Provider(providerName); IEventRecordDelegate callback = (IEventRecord r) => { try { var clientPid = r.GetInt32("ClientProcessId"); if (clientPid == _processId) { var obj = _propertyExtractor.Extract(r); lock (_lock) { _records.Add(obj.ToPSObject()); } } } catch { // TODO: log bad record parse } }; var filter = new EventFilter(Filter.EventIdIs(WMIEventId)); filter.OnEvent += callback; wmiProvider.AddFilter(filter); return(new PSEtwUserProvider(wmiProvider, providerName)); }
public static void Start() { var trace = new UserTrace("UserTrace007_StackTrace"); var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.Any = 0x10; // WINEVENT_KEYWORD_PROCESS provider.TraceFlags |= TraceFlags.IncludeStackTrace; var processFilter = new EventFilter(Filter.EventIdIs(1)); // ProcessStart processFilter.OnEvent += (record) => { var pid = record.GetUInt32("ProcessID"); var imageName = record.GetUnicodeString("ImageName"); Console.WriteLine($"{record.TaskName} pid={pid} ImageName={imageName}\nCallStack:"); foreach (var returnAddress in record.GetStackTrace()) { Console.WriteLine($" 0x{returnAddress.ToUInt64():x}"); } }; provider.AddFilter(processFilter); trace.Enable(provider); trace.Start(); }
static void Main(string[] args) { var filter = new EventFilter(Filter .EventIdIs(3018) .Or(Filter.EventIdIs(3020))); filter.OnEvent += (IEventRecord r) => { var query = r.GetUnicodeString("QueryName"); var result = r.GetUnicodeString("QueryResults"); TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); int secondsSinceEpoch = (int)t.TotalSeconds; Console.WriteLine($"{secondsSinceEpoch} | {r.Id} | {query} | {result}"); }; var provider = new Provider("Microsoft-Windows-DNS-Client"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); Console.CancelKeyPress += (sender, eventArg) => { if (trace != null) { trace.Stop(); } }; trace.Start(); }
static void Main(string[] args) { var trace = new UserTrace(); var processProvider = new Provider("Microsoft-Windows-Kernel-Process"); processProvider.All = 0x40; // Enable the WINEVENT_KEYWORD_IMAGE flag. var filter = new EventFilter(Filter.EventIdIs(5)); filter.OnEvent += (record) => { var dllName = record.GetUnicodeString("ImageName", "<UNKNOWN>"); if (dllName.ToLower().EndsWith("mscoree.dll")) { var pid = record.GetUInt32("ProcessID", 0); var processName = string.Empty; try { processName = System.Diagnostics.Process.GetProcessById((int)pid).ProcessName; } catch (Exception) { } Console.WriteLine($"{processName} (PID: {pid}) loaded .NET runtime ({dllName})"); } }; processProvider.AddFilter(filter); trace.Enable(processProvider); Console.CancelKeyPress += (sender, eventArg) => { if (trace != null) { trace.Stop(); } }; trace.Start(); }
static void Main(string[] args) { var trace = new UserTrace(); // The name of the PowerShell provider that gives us with detailed // method execution logging is "Microsoft-Windows-PowerShell". // // If you want to explore all the events in this provider, // you'll need to use Message Analyzer to load the trace and explore // the events. // // Download: https://www.microsoft.com/en-us/download/details.aspx?id=44226 var powershellProvider = new Provider("Microsoft-Windows-PowerShell"); var powershellFilter = new EventFilter( Filter.EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started"))); powershellFilter.OnEvent += OnEvent; // The "Any" and "All" flags can be sussed out using Microsoft Message Analyzer. powershellProvider.Any = 0x20; powershellProvider.AddFilter(powershellFilter); trace.Enable(powershellProvider); // This is a blocking call. Ctrl-C to stop. trace.Start(); }
private PSEtwUserProvider CreateRegistryProvider() { const string providerName = "Microsoft-Windows-Kernel-Registry"; var registryProvider = new Provider(providerName); var filter = new EventFilter(Filter.ProcessIdIs((int)_processId)); filter.OnEvent += DefaultEventHandler; registryProvider.AddFilter(filter); return(new PSEtwUserProvider(registryProvider, providerName)); }
static void Main(string[] args) { // UserTrace instances should be used for any non-kernel traces that are defined // by components or programs in Windows. They can optionally take a name -- if none // is provided, a random GUID is assigned as the name. var trace = new UserTrace("Silly Gooby"); // A trace can have any number of providers, which are identified by GUID. These // GUIDs are defined by the components that emit events, and their GUIDs can // usually be found with various ETW tools (like wevutil). var powershellProvider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); // UserTrace providers typically have any and all flags, whose meanings are // unique to the specific providers that are being invoked. To understand these // flags, you'll need to look to the ETW event producer. powershellProvider.Any = Provider.AllBitsSet; // In user_trace_001.cs, we manually filter events by checking the information // in our callback functions. In this example, we're going to use a provider // filter to do this for us. // We instantiate an EventFilter first. An EventFilter is created with a predicate -- // literally just a function that does some check on an EventRecord and returns a boolean // (true when the even should be passed on to callbacks, false otherwise). // EventFilters are more than just convenient -- Lobster provides combinators for // expressing simple but powerful filters that actually execute in the underlying C++ // krabs library. This means that events can be filtered before ever running in the // CLR (saving us a ton of cost in spinning up objects on event firing). // The combinators cannot express everything a filter must do, so for complicated // filters, it's recommended to write the filters in a managed C++/CLI project and // use those to keep the perf benefits. The filters that Lobster provides are on // the Filter object (and can be combined with &&, ||, !) var filter = new EventFilter(Filter.EventIdIs(7937)); // EventFilters have attached callbacks, just like a regular provider. filter.OnEvent += (EventRecord record) => { var schema = new Schema(record); System.Diagnostics.Debug.Assert(schema.Id == 7937); Console.WriteLine("Event 7937 received"); }; // EventFilters are attached to providers. Events that are attached to the filter // will only be called when the filter allows the event through. Any events attached // to the provider directly will be called for all events that are fired by the ETW // producer. powershellProvider.AddFilter(filter); trace.Enable(powershellProvider); trace.Start(); }
private PSEtwUserProvider CreatePowerShellProvider() { const string providerName = "Microsoft-Windows-PowerShell"; var powershellProvider = new Provider(providerName); var filter = new EventFilter(Filter.ProcessIdIs((int)_processId) .And(Filter.EventIdIs(7937)) .And(UnicodeString.Contains("Payload", "Started."))); filter.OnEvent += DefaultEventHandler; powershellProvider.AddFilter(filter); return(new PSEtwUserProvider(powershellProvider, providerName)); }
private PSEtwUserProvider CreateFileProvider() { const string providerName = "Microsoft-Windows-Kernel-File"; var fileProvider = new Provider(providerName);; var pidFilter = Filter.ProcessIdIs((int)_processId); var eventIdFilter = Filter.EventIdIs(12).Or(Filter.EventIdIs(30)); var filter = new EventFilter(pidFilter.And(eventIdFilter)); filter.OnEvent += DefaultEventHandler; fileProvider.AddFilter(filter); return(new PSEtwUserProvider(fileProvider, providerName)); }
static void Main(string[] args) { var count = 0; var cts = new CancellationTokenSource(); var trace = new UserTrace("MY AWESOME TEST THING"); //var provider = new RawProvider(EventSource.GetGuid(typeof(TestEventSource))); var provider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); // Only pull in method invocations var powershellFilter = new EventFilter(Filter.EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started"))); powershellFilter.OnEvent += e => { Console.WriteLine($"{e.ProviderName} - {e.Id}: {count++}"); }; provider.AddFilter(powershellFilter); Console.CancelKeyPress += (s, e) => { cts.Cancel(); trace.Stop(); }; trace.Enable(provider); var statsLoop = Task.Run(() => PrintStats(trace, cts.Token)); Task.Run(() => trace.Start()) .ContinueWith(t => Console.WriteLine($"Task ended with status {t.Status}")); Console.WriteLine("Enter to restart trace"); Console.ReadKey(); Task.Run(() => trace.Start()) .ContinueWith(t => Console.WriteLine($"Task ended with status {t.Status}")); Console.WriteLine("Ctrl+C to quit"); statsLoop.Wait(); Console.WriteLine("Done"); }
private PSEtwUserProvider CreateDnsProvider() { const string providerName = "Microsoft-Windows-DNS-Client"; var dnsProvider = new Provider(providerName); const int NXDomainEventId = 1016; const int CachedLookupEventId = 3018; const int LiveLookupEventId = 3020; var eventIdFilter = Filter.EventIdIs(NXDomainEventId) .Or(Filter.EventIdIs(CachedLookupEventId) .Or(Filter.EventIdIs(LiveLookupEventId))); var filter = new EventFilter(eventIdFilter); filter.OnEvent += DefaultEventHandler; dnsProvider.AddFilter(filter); return(new PSEtwUserProvider(dnsProvider, providerName)); }
static void Main(string[] args) { var filter = new EventFilter(Filter .EventIdIs(3018) .Or(Filter.EventIdIs(3020))); filter.OnEvent += (IEventRecord r) => { var query = r.GetUnicodeString("QueryName"); var result = r.GetUnicodeString("QueryResults"); Console.WriteLine($"DNS query ({r.Id}): {query} - {result}"); }; var provider = new Provider("Microsoft-Windows-DNS-Client"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); trace.Start(); }
private PSEtwUserProvider CreateNetworkProvider() { const string providerName = "Microsoft-Windows-Kernel-Network"; var networkProvider = new Provider(providerName); const int IPv4TcpSend = 10; const int IPv6TcpSend = 26; const int IPv4UdpSend = 42; const int IPv6UdpSend = 58; var processIdFilter = Filter.ProcessIdIs((int)_processId); var eventIdFilter = Filter.EventIdIs(IPv4TcpSend) .Or(Filter.EventIdIs(IPv6TcpSend) .Or(Filter.EventIdIs(IPv4UdpSend) .Or(Filter.EventIdIs(IPv6UdpSend)))); var filter = new EventFilter(processIdFilter.And(eventIdFilter)); filter.OnEvent += DefaultEventHandler; networkProvider.AddFilter(filter); return(new PSEtwUserProvider(networkProvider, providerName)); }
static void Main(string[] args) { var filter = new EventFilter( Filter.EventIdIs(5) //.Or(Filter.EventIdIs(6)) ); // Microsoft-Windows-RPC EventID 5 - Client RPC call started // EventID 6 - Server RPC call started. filter.OnEvent += (IEventRecord r) => { var endpoint = r.GetUnicodeString("Endpoint"); var opNum = r.GetUInt32("ProcNum"); var protocol = r.GetUInt32("Protocol"); Console.WriteLine($"RPC Event {r.Id}"); Console.WriteLine($"Endpoint: {endpoint}"); Console.WriteLine($"Protocol {protocol,0:X}"); Console.WriteLine($"OpNum: {opNum}"); }; var provider = new Provider("Microsoft-Windows-RPC"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); Console.CancelKeyPress += (sender, eventArg) => { if (trace != null) { trace.Stop(); } }; trace.Start(); }
public static void Start() { // UserTrace instances should be used for any non-kernel traces that are defined // by components or programs in Windows. They can optionally take a name -- if none // is provided, a random GUID is assigned as the name. var trace = new UserTrace(); // A trace can have any number of providers, which are identified by GUID. These // GUIDs are defined by the components that emit events, and their GUIDs can // usually be found with various ETW tools (like wevutil). var powershellProvider = new Provider(Guid.Parse("{A0C1853B-5C40-4B15-8766-3CF1C58F985A}")); // UserTrace providers typically have any and all flags, whose meanings are // unique to the specific providers that are being invoked. To understand these // flags, you'll need to look to the ETW event producer. powershellProvider.Any = Provider.AllBitsSet; // In UserTrace003.cs, we use ETW-based filtering to select a specific event ID. // // We can combine ETW-based filtering with predicate filters to filter on specific // event properties without impacting performance. var filter = new EventFilter(7937, UnicodeString.Contains("ContextInfo", "Write-Host")); // EventFilters have attached callbacks, just like a regular provider. filter.OnEvent += (record) => { System.Diagnostics.Debug.Assert(record.Id == 7937); Console.WriteLine(record.GetUnicodeString("ContextInfo")); }; // EventFilters are attached to providers. Events that are attached to the filter // will only be called when the filter allows the event through. Any events attached // to the provider directly will be called for all events that are fired by the ETW // producer. powershellProvider.AddFilter(filter); trace.Enable(powershellProvider); trace.Start(); }
internal void AddFilter(PSEtwFilter filter) { _filters.Add(filter); _provider.AddFilter(filter.Filter); }
private PSEtwUserProvider CreateProcessProvider() { const string providerName = "Microsoft-Windows-Kernel-Process"; var processProvider = new Provider(providerName); // process start/stop var startStopFilter = new EventFilter(Filter.EventIdIs(1).Or(Filter.EventIdIs(2))); startStopFilter.OnEvent += (IEventRecord r) => { try { if (r.Id == 1) { var parentProcessId = r.GetUInt32("ParentProcessID"); if (parentProcessId == _processId) { var obj = _propertyExtractor.Extract(r); lock (_lock) { _records.Add(obj.ToPSObject()); } } } else if (r.Id == 2 && r.ProcessId == _processId) { var obj = _propertyExtractor.Extract(r); lock (_lock) { _records.Add(obj.ToPSObject()); } const int secondsToWait = 10; // We wait ten seconds to give ourselves a chance to process // any remaining items relevant to the process. Task.Run(() => { Thread.Sleep(TimeSpan.FromSeconds(secondsToWait)); _cts.Cancel(); }); } } catch (Exception ex) { Console.WriteLine($"{ex.Message}\n{ex.StackTrace}"); // TODO: log bad record parse } }; processProvider.AddFilter(startStopFilter); // image load var imageLoadFilter = new EventFilter(Filter.ProcessIdIs((int)_processId).And(Filter.EventIdIs(5))); imageLoadFilter.OnEvent += DefaultEventHandler; processProvider.AddFilter(imageLoadFilter); // thread injection var threadFilter = new EventFilter(Filter.ProcessIdIs((int)_processId).And(Filter.EventIdIs(3))); threadFilter.OnEvent += (IEventRecord r) => { try { var targetProcessId = (int)r.GetUInt32("ProcessID"); if (targetProcessId != r.ProcessId) { var targetProcess = Process.GetProcessById(targetProcessId); var targetProcessName = targetProcess.MainModule.FileName; // If the process start for the target process is more than // 10 milliseconds after the thread creation time, then it // is a good chance this is not the initial thread. var diff = r.Timestamp.Subtract(targetProcess.StartTime); if (diff.TotalMilliseconds > 10) { var obj = _propertyExtractor.Extract(r); obj.Add("TargetProcessName", targetProcessName); lock (_lock) { _records.Add(obj.ToPSObject()); } } } } catch { // TODO: log bad record parse } }; processProvider.AddFilter(threadFilter); return(new PSEtwUserProvider(processProvider, providerName)); }
static void Main(string[] args) { bool start = false; Injected_Processes_IDsList.Add("0"); Injected_Processes_IDsList.Add("0"); Console.CancelKeyPress += Console_CancelKeyPress; Temp_Thread_InfoDebugMode = new DataTable(); Temp_Thread_InfoDebugMode.Columns.Add("tid", typeof(int)); Temp_Thread_InfoDebugMode.Columns.Add("Time_Negative"); Temp_Thread_InfoDebugMode.Columns.Add("status"); Temp_Thread_InfoDebugMode.Columns.Add("tid_StartAddress_x64"); Temp_Thread_InfoDebugMode.Columns.Add("StartTime"); Temp_Thread_InfoDebugMode.Columns.Add("Proc_Name"); Temp_Thread_InfoDebugMode.Columns.Add("Proc_id"); Temp_Thread_InfoDebugMode.Columns.Add("IsNewProcess"); Temp_Thread_InfoDebugMode.Columns.Add("tid_StartAddress"); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(); Console.WriteLine("ETWMonThread 1.0 (x64 only) "); Console.WriteLine("Realtime Scanning/Monitoring Thread Injection for MPD (Meterpreter Payload Detection) by ETW"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Published by Damon Mohammadbagher Jan 2018"); if (args.Length == 0) { start = true; } if (args.Length == 1) { if (args[0].ToUpper() == "IPS") { IPS_IDS = true; start = true; } else { IPS_IDS = false; start = true; } if (args[0].ToUpper() == "SHOWALL") { IsShowAllRecrds = true; start = true; } } if (args.Length >= 2) { if (args[0].ToUpper() == "IPS" && args[1].ToUpper() == "DEBUG") { IPS_IDS = true; Is_DebugMode = true; start = true; } if (args[0].ToUpper() == "SHOWALL" && args[1].ToUpper() == "DEBUG") { IsShowAllRecrds = true; Is_DebugMode = true; start = true; } } if (args.Length >= 1) { if (args[0].ToUpper() == "HELP") { start = false; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(); Console.WriteLine("[!] ETWMonThread , Realtime Scanning/Monitoring Thread Injection for MPD (Meterpreter Payload Detection) by ETW"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[!] Syntax 1: Realtime Scanning/Monitoring IPS Mode (Killing Meterpreter Injected Threads)"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[!] Syntax 1: ETWMonThread.exe \"IPS\" [optional] \"DEBUG\""); Console.WriteLine("[!] Example1: ETWMonThread.exe IPS "); Console.WriteLine("[!] Example2: ETWMonThread.exe IPS DEBUG"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[!] Syntax 2: Realtime Monitoring IDS Mode"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[!] Syntax 2: ETWMonThread.exe [optional] \"SHOWALL\" [optional] \"DEBUG\" "); Console.WriteLine("[!] Example1: ETWMonThread.exe"); Console.WriteLine("[!] Example2: ETWMonThread.exe SHOWALL"); Console.WriteLine("[!] Example3: ETWMonThread.exe SHOWALL DEBUG"); Console.ForegroundColor = ConsoleColor.Gray; } } if (start) { Console.WriteLine(); if (IPS_IDS) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[!] Realtime Scanning/Monitoring IPS Mode (warning : Killing Threads)"); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[!] Realtime Monitoring IDS Mode"); Console.ForegroundColor = ConsoleColor.Gray; } /// EventID 3 is for "Thread Created" var ETWEventsFilter = new EventFilter(Filter.EventIdIs(3)); ETWEventsFilter.OnEvent += ETWEventsFilter_OnEvent; P.OnError += P_OnError; P.AddFilter(ETWEventsFilter); T.Enable(P); T.Start(); } }