### Monitor WMI Activity with pywintrace Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt This Python script monitors the 'Microsoft-Windows-WMI-Activity' ETW provider to capture WMI query operations and provider start events. It uses the psutil library to retrieve process information. The script filters for specific Event IDs (11 and 5857) and prints formatted output detailing WMI queries and provider status. ```python import etw import psutil from datetime import datetime def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def wmi_handler(x): data = x[1] time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') eid = int(data['EventHeader']['EventDescriptor']['Id']) pid = int(data['EventHeader']['ProcessId']) process_name, cmdline = getProcess(pid) if eid == 11: # WMI Query Operation Operation = data["Operation"] ClientMachine = data["ClientMachine"] User = data["User"] ClientProcessId = int(data['ClientProcessId']) NamespaceName = data["NamespaceName"] client_name, _ = getProcess(ClientProcessId) print(f"[{time}] WMI QUERY:") print(f" User: {User} on {ClientMachine}") print(f" Client: {client_name} (PID:{ClientProcessId})") print(f" Namespace: {NamespaceName}") print(f" Operation: {Operation}") elif eid == 5857: # WMI Provider Started ProviderName = data["ProviderName"] HostProcess = data["HostProcess"] ProcessID = data["ProcessID"] ProviderPath = data["ProviderPath"] print(f"[{time}] WMI PROVIDER STARTED: {ProviderName}") print(f" Host: {HostProcess} (PID:{ProcessID})") print(f" Path: {ProviderPath}") def main(): name = "Microsoft-Windows-WMI-Activity" guid = "{1418EF04-B0B4-4623-BF7E-D74AB47BBDAA}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] # EID 11: Query, EID 12: Provider Info, EID 5857: Provider Start with etw.ETW(providers=providers, event_callback=lambda x: wmi_handler(x), event_id_filters=[11, 12, 5857]): etw.run('etw') if __name__ == '__main__': main() ``` -------------------------------- ### Monitor Comprehensive Kernel Process Lifecycle Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Tracks process creation, thread starts, and image loads using the Microsoft-Windows-Kernel-Process provider. It extracts detailed metadata such as token elevation status, command lines, and memory addresses. ```python import etw import psutil from datetime import datetime def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def kernel_process_handler(x): data = x[1] time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') eid = int(data['EventHeader']['EventDescriptor']['Id']) if eid == 1: # Process Creation ProcessID = int(data["ProcessID"]) ParentProcessID = int(data["ParentProcessID"]) ImageName = data["ImageName"] ProcessTokenIsElevated = data["ProcessTokenIsElevated"] process_name, cmdline = getProcess(ProcessID) parent_name, _ = getProcess(ParentProcessID) print(f"[{time}] Process Created: PID: {ProcessID} ({process_name}), Parent: {ParentProcessID} ({parent_name}), Elevated: {ProcessTokenIsElevated}") elif eid == 3: # Thread Start print(f"[{time}] Thread {data['ThreadID']} started in PID {data['ProcessID']}") elif eid == 5: # Image Load print(f"[{time}] Image loaded: {data['ImageName']} in PID {data['ProcessID']}") def main(): name = "Microsoft-Windows-Kernel-Process" guid = "{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] with etw.ETW(providers=providers, event_callback=lambda x: kernel_process_handler(x), event_id_filters=[1, 3, 5]): etw.run('etw') if __name__ == '__main__': main() ``` -------------------------------- ### Define Common ETW Provider GUIDs in Python Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt This Python dictionary maps common Windows ETW provider names to their corresponding GUIDs. These GUIDs are crucial for subscribing to specific event streams for security monitoring and analysis. ```python ETW_PROVIDERS = { # Kernel Providers "Microsoft-Windows-Kernel-Process": "{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}", "Microsoft-Windows-Kernel-Network": "{7DD42A49-5329-4832-8DFD-43D979153A88}", "Microsoft-Windows-Kernel-File": "{EDD08927-9CC4-4E65-B970-C2560FB5C289}", "Microsoft-Windows-Kernel-Registry": "{70EB4F03-C1DE-4F73-A051-33D13D5413BD}", # Security Providers "Microsoft-Windows-Security-Auditing": "{54849625-5478-4994-A5BA-3E3B0328C30D}", "Microsoft-Windows-Threat-Intelligence": "{F4E1897C-BB5D-5668-F1D8-040F4D8DD344}", # Service/Component Providers "Microsoft-Windows-WMI-Activity": "{1418EF04-B0B4-4623-BF7E-D74AB47BBDAA}", "Microsoft-Windows-LDAP-Client": "{099614A5-5DD7-4788-8BC9-E29F43DB28FC}", "Microsoft-Windows-RPC": "{6AD52B32-D609-4BE9-AE07-CE8DAE937E39}", "Microsoft-Windows-DNS-Client": "{1C95126E-7EEA-49A9-A3FE-A378B03DDB4D}", "Microsoft-Windows-PowerShell": "{A0C1853B-5C40-4B15-8766-3CF1C58F985A}", "Microsoft-Windows-Sysmon": "{5770385F-C22A-43E0-BF4C-06F5698FFBD9}", # Authentication Providers "Microsoft-Windows-Kerberos-Key-Distribution-Center": "{24DB8964-E6BC-11D1-916A-0000F8045B04}", "Microsoft-Windows-NTLM": "{AC43300D-5FCC-4800-8E99-1BD3F85F0320}", } ``` -------------------------------- ### Monitor LDAP Client Activity with pywintrace Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt This Python script monitors the 'Microsoft-Windows-LDAP-Client' ETW provider to detect LDAP query activities. It uses psutil to get process names and command lines. The script focuses on Event ID 30 (LDAP Search Request) and extracts details like scope, base DN, filter, and attributes, which are useful for identifying Active Directory reconnaissance. ```python # File: Examples/pywintrace/ETW Providers/LDAP-Client.py import etw import psutil from datetime import datetime def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def ldap_handler(x): data = x[1] time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') ScopeOfSearch = data["ScopeOfSearch"] SearchFilter = data["SearchFilter"] DistinguishedName = data["DistinguishedName"] AttributeList = data["AttributeList"] ProcessId = int(data["ProcessId"], 16) process_name, cmdline = getProcess(ProcessId) print(f"[{time}] LDAP QUERY:") print(f" Process: {process_name} (PID:{ProcessId})") print(f" Scope: {ScopeOfSearch}") print(f" Base DN: {DistinguishedName}") print(f" Filter: {SearchFilter}") print(f" Attributes: {AttributeList}") def main(): name = "Microsoft-Windows-LDAP-Client" guid = "{099614A5-5DD7-4788-8BC9-E29F43DB28FC}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] # EID 30: LDAP Search Request with etw.ETW(providers=providers, event_callback=lambda x: ldap_handler(x), event_id_filters=[30]): etw.run('etw') if __name__ == '__main__': main() # Example output detecting AD enumeration: # [2024-01-15 14:22:33] LDAP QUERY: # Process: powershell.exe (PID:4567) # Scope: Subtree # Base DN: DC=contoso,DC=com # Filter: (&(objectClass=user)(adminCount=1)) # Attributes: samaccountname,memberof ``` -------------------------------- ### Define ETW Provider Manifest XML Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt An example of an XML schema definition for an ETW provider, detailing GUIDs, channels, and event metadata. This structure is used to parse and understand Windows event logs. ```xml Microsoft-Windows-Security-Auditing {54849625-5478-4994-A5BA-3E3B0328C30D} %SystemRoot%\system32\adtschema.dll %SystemRoot%\system32\msobjs.dll %SystemRoot%\system32\adtschema.dll Microsoft Windows security auditing. Security Security 0 10 4608 0 Information Security Windows is starting up. ``` -------------------------------- ### Monitor Multiple ETW Providers in Python Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt This Python function demonstrates how to subscribe to and monitor multiple ETW providers simultaneously using the `etw` library. It defines a list of `ProviderInfo` objects and sets up an event callback to process incoming events. ```python import etw def multi_provider_monitor(): providers = [ etw.ProviderInfo("Microsoft-Windows-Kernel-Process", etw.GUID("{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}")), etw.ProviderInfo("Microsoft-Windows-Kernel-Network", etw.GUID("{7DD42A49-5329-4832-8DFD-43D979153A88}")), etw.ProviderInfo("Microsoft-Windows-DNS-Client", etw.GUID("{1C95126E-7EEA-49A9-A3FE-A378B03DDB4D}")), ] with etw.ETW(providers=providers, event_callback=lambda x: print(x)): etw.run('etw') ``` -------------------------------- ### Monitor Process Creation with ETW Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Captures process creation events using the Microsoft-Windows-Kernel-Process provider. It utilizes the psutil library to correlate PIDs with process names and parent-child relationships. ```python import etw import psutil def process_creation_handler(data): event = data[1] pid = int(event["ProcessID"]) ppid = int(event["EventHeader"]["ProcessId"]) process_name = "" parent_process_name = "" for process in psutil.process_iter(): if process.pid == pid: process_name = process.name() if process.pid == ppid: parent_process_name = process.name() print(f'"{parent_process_name}" (PPID: {ppid}) Created: "{process_name}" (PID: {pid})') def main(): name = "Microsoft-Windows-Kernel-Process" GUID = "{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}" providers = [etw.ProviderInfo(name, etw.GUID(GUID))] with etw.ETW(providers=providers, event_callback=lambda d: process_creation_handler(d), event_id_filters=[1]): etw.run('etw') if __name__ == '__main__': main() ``` -------------------------------- ### Query ETW Event CSV Data Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Demonstrates how to search consolidated ETW provider CSV files using PowerShell. This allows analysts to filter for specific Event IDs across different Windows versions and builds. ```powershell Import-Csv "ETWProvidersCSVs/Internal/Microsoft-Windows-Security-Auditing.csv" | Where-Object { $_."Event ID" -eq "4688" } | Select-Object Windows, Version, Build -Unique ``` -------------------------------- ### Format ETW Event Catalog CSV Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt A sample structure of the version-specific event catalogs provided in the repository. These files aggregate provider information, event IDs, and message templates for comprehensive analysis. ```csv Provider,Level,Event ID,Version,Channel,Task,Opcode,Keyword,Message Microsoft-Windows-Security-Auditing,Information,4608,0,Security,,,,"Windows is starting up." Microsoft-Windows-Security-Auditing,Information,4624,0,Security,Logon,,,"An account was successfully logged on." Microsoft-Windows-Kernel-Process,Information,1,0,,,ProcessStart,,"Process {ProcessID} started" Microsoft-Windows-Kernel-Network,Information,10,0,,,Send,,"TCPv4: bytes transmitted" ``` -------------------------------- ### Monitor Kernel File Operations with Python Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Monitors file creation (EID 30) and deletion (EID 11) events from the Microsoft-Windows-Kernel-File ETW provider. It uses the 'etw' and 'psutil' libraries to process event data and retrieve process information, excluding events from the monitoring process itself. Events are filtered by EID (10, 11, 30). ```python # File: Examples/pywintrace/ETW Providers/Kernel-File.py import etw import psutil from datetime import datetime import os def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def file_handler(x): data = x[1] pid = int(data['EventHeader']['ProcessId']) # Skip events from this monitoring process if pid == os.getpid(): return time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') eid = int(data['EventHeader']['EventDescriptor']['Id']) process_name, cmdline = getProcess(pid) if eid == 11: # File Delete FileName = data["FileName"] print(f"[{time}] FILE DELETE: {process_name} (PID:{pid}) deleted {FileName}") elif eid == 30: # File Create FileName = data["FileName"] CreateOptions = data["CreateOptions"] ShareAccess = data["ShareAccess"] print(f"[{time}] FILE CREATE: {process_name} (PID:{pid}) created {FileName}") print(f" Options: {CreateOptions}, Share: {ShareAccess}") def main(): name = "Microsoft-Windows-Kernel-File" guid = "{EDD08927-9CC4-4E65-B970-C2560FB5C289}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] # EID 10: Read, EID 11: Delete, EID 30: Create with etw.ETW(providers=providers, event_callback=lambda x: file_handler(x), event_id_filters=[10, 11, 30]): etw.run('etw') if __name__ == '__main__': main() ``` -------------------------------- ### Monitor Kernel Network Events with Python Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Captures and logs TCP send, receive, connect attempt, and established events from the Microsoft-Windows-Kernel-Network ETW provider. It uses the 'etw' and 'psutil' libraries to process event data and retrieve process information. Events are filtered by EID (10, 11, 12, 15). ```python import etw import psutil from datetime import datetime def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def network_handler(x): data = x[1] time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') eid = int(data['EventHeader']['EventDescriptor']['Id']) PID = int(data["PID"]) Size = data["size"] daddr = data["daddr"] # Destination address saddr = data["saddr"] # Source address dport = data["dport"] # Destination port sport = data["sport"] # Source port process_name, _ = getProcess(PID) if eid == 10: print(f"[{time}] TCP SEND: {process_name} (PID:{PID}) {saddr}:{sport} -> {daddr}:{dport} ({Size} bytes)") elif eid == 11: print(f"[{time}] TCP RECV: {process_name} (PID:{PID}) {saddr}:{sport} <- {daddr}:{dport} ({Size} bytes)") elif eid == 12: print(f"[{time}] TCP CONNECT ATTEMPT: {process_name} (PID:{PID}) {saddr}:{sport} -> {daddr}:{dport}") elif eid == 15: print(f"[{time}] TCP ESTABLISHED: {process_name} (PID:{PID}) {saddr}:{sport} <-> {daddr}:{dport}") def main(): name = "Microsoft-Windows-Kernel-Network" guid = "{7DD42A49-5329-4832-8DFD-43D979153A88}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] # EID 10: Send, EID 11: Receive, EID 12: Connect attempt, EID 15: Established with etw.ETW(providers=providers, event_callback=lambda x: network_handler(x), event_id_filters=[10, 11, 12, 15]): etw.run('etw') if __name__ == '__main__': main() ``` -------------------------------- ### Convert ETW XML Manifests to CSV Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Parses ETW provider XML files to extract event metadata such as Event ID, Task, and Message. The resulting data is exported to a CSV file for easier ingestion into analysis tools. ```python import xml.etree.ElementTree as ET import csv def parse_etw_xml(file_path): root = ET.parse(file_path).getroot() try: provider_name = root[0][0].text if root[0][0].tag == "Name" else "" eventMetaData = root[0][2] if root[0][2].tag == "EventMetadata" else None except IndexError: return None events_list = [] for event in eventMetaData: event_dict = {'eid': event[0].text, 'channel': '', 'message': '', 'version': '', 'level': '', 'task': '', 'opcode': '', 'keyword': ''} for data in event: if data.tag in event_dict: event_dict[data.tag.lower()] = data.text.replace("\n", "").replace(",", ";") if data.text else "" elif data.tag == "Message": event_dict['message'] = data.text.replace("\n", "").replace(",", ";").replace('"', "'") if data.text else "" events_list.append(event_dict) return {"provider_name": provider_name, "events": events_list} def convert_to_csv(parsed_provider, output_path): header = "Provider,Level,Event ID,Version,Channel,Task,Opcode,Keyword,Message" with open(output_path, "w") as f: f.write(header + "\n") for event in parsed_provider["events"]: row = f'{parsed_provider["provider_name"]},{event["level"]},{event["eid"]},' row += f'{event["version"]},{event["channel"]},{event["task"]},' row += f'{event["opcode"]},{event["keyword"]},{event["message"]}' f.write(row + "\n") ``` -------------------------------- ### Monitor RPC ETW Events Source: https://context7.com/nasbench/evtx-etw-resources/llms.txt Captures and logs real-time RPC (Remote Procedure Call) events using the Microsoft-Windows-RPC provider. It maps event IDs to process names and prints detailed call information including interface UUIDs and authentication levels. ```python import etw import psutil from datetime import datetime def getProcess(pid): for proc in psutil.process_iter(): if proc.pid == pid: return proc.name(), " ".join(proc.cmdline()) return "", "" def rpc_handler(x): data = x[1] time = int(data['EventHeader']["TimeStamp"]) time = datetime.utcfromtimestamp(time / (10*1000*1000)-11644473600).strftime('%Y-%m-%d %H:%M:%S') eid = int(data['EventHeader']['EventDescriptor']['Id']) pid = int(data['EventHeader']['ProcessId']) InterfaceUuid = data["InterfaceUuid"] ProcNum = int(data["ProcNum"], 16) Protocol = data["Protocol"] NetworkAddress = data["NetworkAddress"] Endpoint = data["Endpoint"] AuthenticationLevel = data["AuthenticationLevel"] AuthenticationService = data["AuthenticationService"] process_name, _ = getProcess(pid) call_type = "SERVER RPC" if eid == 5 else "CLIENT RPC" print(f"[{time}] {call_type}:") print(f" Process: {process_name} (PID:{pid})") print(f" Interface: {InterfaceUuid}") print(f" Procedure: {ProcNum}") print(f" Protocol: {Protocol}") print(f" Network: {NetworkAddress}:{Endpoint}") print(f" Auth: Level={AuthenticationLevel}, Service={AuthenticationService}") def main(): name = "Microsoft-Windows-RPC" guid = "{6AD52B32-D609-4BE9-AE07-CE8DAE937E39}" providers = [etw.ProviderInfo(name, etw.GUID(guid))] with etw.ETW(providers=providers, event_callback=lambda x: rpc_handler(x), event_id_filters=[5, 6]): etw.run('etw') if __name__ == '__main__': main() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.