def listen(self, honeypot_configuration): h = win32event.CreateEvent(None, 0, 0, None) s = win32evtlog.EvtSubscribe( self.log_type, win32evtlog.EvtSubscribeStartAtOldestRecord, SignalEvent=h, Query=self.query_text) while True: while True: events = win32evtlog.EvtNext(s, 10) if len(events) == 0: break for event in events: event_id = None event_format_xml = win32evtlog.EvtRender( event, win32evtlog.EvtRenderEventXml) event_format_dict = xmltodict.parse(event_format_xml) if isinstance( event_format_dict['Event']['System']['EventID'], str): event_id = event_format_dict['Event']['System'][ 'EventID'] else: event_id = event_format_dict['Event']['System'][ 'EventID']['#text'] honeypot = self.__identify_honeypot( event_id, event_format_xml, honeypot_configuration) if honeypot is not None: self.__alert(event_format_dict, event_id, honeypot) while True: print("Waiting " + self.log_type) w = win32event.WaitForSingleObjectEx(h, 10000, True) if w == win32con.WAIT_OBJECT_0: break
def register_listener(callback_func=print_event): ''' 开始监听Sysmon事件,当事件发生的时候调用监听函数。 ''' query_text = "*" channel_path = "Microsoft-Windows-Sysmon/Operational" h_evt = win32event.CreateEvent(None, 0, 0, None) h_sub = win32evtlog.EvtSubscribe(channel_path, win32evtlog.EvtSubscribeToFutureEvents, SignalEvent=h_evt, Query=query_text) print("开始监听可疑事件") while True: while True: events = win32evtlog.EvtNext(h_sub, 10) if len(events) == 0: break # print('retrieved %s events' %len(events)) for event in events: callback_func(event) while True: # print ('waiting...') w = win32event.WaitForSingleObjectEx(h_evt, 2000, True) if w == win32con.WAIT_OBJECT_0: break
def poll_events(self): while True: # IMPORTANT: the subscription starts immediately so you must consume before waiting for the first signal while True: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtnext # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtNext_meth.html try: events = win32evtlog.EvtNext(self._subscription, self._payload_size) except pywintypes.error as e: self.log_windows_error(e) break else: if not events: break for event in events: yield event # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobjectex # http://timgolden.me.uk/pywin32-docs/win32event__WaitForSingleObjectEx_meth.html wait_signal = win32event.WaitForSingleObjectEx( self._event_handle, self._timeout, True) # No more events, end check run if wait_signal != win32con.WAIT_OBJECT_0: break
def poll_events(self): while True: # IMPORTANT: the subscription starts immediately so you must consume before waiting for the first signal while True: # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtnext # https://mhammond.github.io/pywin32/win32evtlog__EvtNext_meth.html # # An error saying EvtNext: The operation identifier is not valid happens # when you call the method and there are no events to read (i.e. polling). # There is an unreleased upstream contribution to return # an empty tuple instead https://github.com/mhammond/pywin32/pull/1648 # For the moment is logged as a debug line. try: events = win32evtlog.EvtNext(self._subscription, self.config.payload_size) except pywintypes.error as e: self.log_windows_error(e) break else: if not events: break for event in events: yield event # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobjectex # https://mhammond.github.io/pywin32/win32event__WaitForSingleObjectEx_meth.html wait_signal = win32event.WaitForSingleObjectEx( self._event_handle, self.config.timeout, True) # No more events, end check run if wait_signal != win32con.WAIT_OBJECT_0: break
def subscribe_and_yield_events(channel, query="*"): #SUBSCRIBE h = win32event.CreateEvent(None, 0, 0, None) s = win32evtlog.EvtSubscribe(channel, win32evtlog.EvtSubscribeToFutureEvents, SignalEvent=h, Query=query) #LOOP while True: while True: events = win32evtlog.EvtNext(s, 10) if len(events) == 0: break for event in events: raw_xml = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml) er = LogEvent(raw_xml, source_os=detect_current_os()) if er.is_valid(): yield er else: print("[ERROR] Parsing error") while True: #print('waiting...') w = win32event.WaitForSingleObjectEx(h, 200, True) if w == win32con.WAIT_OBJECT_0: break
def _update_wsl_distros(): global ctx, registry_key_handle, wsl_distros, registry_access_flags # make sure registry is open if not registry_key_handle: _initialize_key() distro_handle = None try: # check for registry changes result = win32event.WaitForSingleObjectEx(key_event, 0, False) # for testing if False: print( f"WAIT - {result=} (looking for 'win32con.WAIT_OBJECT_0')") print(f'WAIT - {win32con.WAIT_OBJECT_0=})') print(f'WAIT - {win32con.WAIT_ABANDONED=})') print(f'WAIT - {win32con.WAIT_TIMEOUT=})') if result == win32con.WAIT_OBJECT_0: # registry has changed since we last read it, load the distros subkeys = win32api.RegEnumKeyEx(registry_key_handle) for subkey in subkeys: #print(f'{subkey=}') distro_handle = win32api.RegOpenKeyEx( registry_key_handle, subkey[0], 0, registry_access_flags) #print(f"{distro_handle=}") distro_name = win32api.RegQueryValueEx( distro_handle, 'DistributionName')[0] #print(f'{distro_name=}') wsl_distros.append(distro_name) win32api.RegCloseKey(distro_handle) # reset the event, will be set by system if reg key changes win32event.ResetEvent(key_event) elif result != win32con.WAIT_TIMEOUT: # something unexpected happened error = win32api.GetLastError() _close_key() raise Exception( 'failed while checking for wsl registry updates: {result=}: {error=}' ) except WindowsError: if distro_handle: win32api.RegCloseKey(distro_handle) log_exception(f'[_update_wsl_distros()] {sys.exc_info()[1]}')
## Demonstrates how to create a "pull" subscription import win32evtlog, win32event, win32con query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]' h = win32event.CreateEvent(None, 0, 0, None) s = win32evtlog.EvtSubscribe('System', win32evtlog.EvtSubscribeStartAtOldestRecord, SignalEvent=h, Query=query_text) while 1: while 1: events = win32evtlog.EvtNext(s, 10) if len(events) == 0: break ##for event in events: ## print(win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml)) print('retrieved %s events' % len(events)) while 1: print('waiting...') w = win32event.WaitForSingleObjectEx(h, 2000, True) if w == win32con.WAIT_OBJECT_0: break