def load_checkpoints(self, checkpoints, config): # open a remote session if needed - we do this before creating the bookmarks and event subscriptions, # because this method could fail with an Exception, so check to see if we can actually connect before # doing any further work. # Assign the result to a member variable so that the session remains open for the lifetime of the object self._session = self._open_remote_session_if_necessary( self._server, config) # only use new checkpoints if 'api' not in checkpoints or checkpoints['api'] != 'new': checkpoints = {} self._checkpoints['api'] = 'new' self._checkpoints['bookmarks'] = {} if 'bookmarks' not in checkpoints: checkpoints['bookmarks'] = {} for channel, bookmarkXml in checkpoints['bookmarks'].iteritems(): self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( bookmarkXml) # subscribe to the events self._subscribe_to_events() # make sure we have at least one successfully subscribed channel if len(self.__eventHandles) == 0: raise Exception("Failed to subscribe to any channels")
def create_subscription(self): # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventa # http://timgolden.me.uk/pywin32-docs/win32event__CreateEvent_meth.html self._event_handle = win32event.CreateEvent(None, 0, 0, self.check_id) bookmark = self.read_persistent_cache('bookmark') if bookmark: flags = win32evtlog.EvtSubscribeStartAfterBookmark else: flags = self.START_OPTIONS[self._subscription_start] # Set explicitly to None rather than a potentially empty string bookmark = None # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreatebookmark # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtCreateBookmark_meth.html self._bookmark_handle = win32evtlog.EvtCreateBookmark(bookmark) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtsubscribe # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtSubscribe_meth.html self._subscription = win32evtlog.EvtSubscribe( self._path, flags, SignalEvent=self._event_handle, Query=self._query, Session=self._session, Bookmark=self._bookmark_handle if bookmark else None, ) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreaterendercontext # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_render_context_flags self._render_context_system = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) self._render_context_data = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextUser)
def load_checkpoints( self, checkpoints ): # only use new checkpoints if 'api' not in checkpoints or checkpoints['api'] != 'new': checkpoints = {} self._checkpoints['api'] = 'new' self._checkpoints['bookmarks'] = {} if 'bookmarks' not in checkpoints: checkpoints['bookmarks'] = {} for channel, bookmarkXml in checkpoints['bookmarks'].iteritems(): self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( bookmarkXml ) # subscribe to channels for info in self.__channels: channel_list = info['channel'] query = info['query'] for channel in channel_list: self._logger.info( "subscribing to %s, %s", channel, query ) # subscribe to future events flags = win32evtlog.EvtSubscribeToFutureEvents bookmark = None try: # unless we have a bookmark for this channel self.__bookmark_lock.acquire() if channel in self.__bookmarks: flags = win32evtlog.EvtSubscribeStartAfterBookmark bookmark = self.__bookmarks[channel] finally: self.__bookmark_lock.release() self.__eventHandles.append( win32evtlog.EvtSubscribe( channel, flags, Bookmark=bookmark, Query=query, Callback=event_callback, Context=self ) )
def log_event(self, event): render_context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) vals = self.GetFormattedEventAsDict(render_context, event) provider = "not-specified" if "ProviderName" in vals: provider = vals["ProviderName"] if "ProviderGuid" in vals: vals["ProviderGuid"] = six.text_type(vals["ProviderGuid"]) if "ActivityId" in vals: vals["ActivityId"] = six.text_type(vals["ActivityId"]) if "RelatedActivityId" in vals: vals["RelatedActivityId"] = six.text_type( vals["RelatedActivityId"]) if "TimeCreated" in vals: time_format = "%Y-%m-%d %H:%M:%SZ" vals["TimeCreated"] = time.strftime( time_format, time.gmtime(int(vals["TimeCreated"]))) if "Keywords" in vals: if isinstance(vals["Keywords"], list): vals["Keywords"] = ",".join(vals["Keywords"]) else: vals["Keywords"] = six.text_type(vals["Keywords"]) if "UserId" in vals: user_id = six.text_type(vals["UserId"]) if user_id.startswith("PySID:"): user_id = user_id[6:] vals["UserId"] = user_id self._logger.emit_value("EventLog", provider, extra_fields=vals) self.__bookmark_lock.acquire() try: if "Channel" in vals: channel = vals["Channel"] bookmark = None if channel not in self.__bookmarks: self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( None) bookmark = self.__bookmarks[channel] win32evtlog.EvtUpdateBookmark(bookmark, event) finally: self.__bookmark_lock.release()
def log_event(self, event): render_context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) vals = self.GetFormattedEventAsDict(render_context, event) provider = 'not-specified' if 'ProviderName' in vals: provider = vals['ProviderName'] if 'ProviderGuid' in vals: vals['ProviderGuid'] = str(vals['ProviderGuid']) if 'ActivityId' in vals: vals['ActivityId'] = str(vals['ActivityId']) if 'RelatedActivityId' in vals: vals['RelatedActivityId'] = str(vals['RelatedActivityId']) if 'TimeCreated' in vals: time_format = "%Y-%m-%d %H:%M:%SZ" vals['TimeCreated'] = time.strftime( time_format, time.gmtime(int(vals['TimeCreated']))) if 'Keywords' in vals: if isinstance(vals['Keywords'], list): vals['Keywords'] = ','.join(vals['Keywords']) else: vals['Keywords'] = str(vals['Keywords']) if 'UserId' in vals: user_id = str(vals['UserId']) if user_id.startswith("PySID:"): user_id = user_id[6:] vals['UserId'] = user_id self._logger.emit_value("EventLog", provider, extra_fields=vals) self.__bookmark_lock.acquire() try: if 'Channel' in vals: channel = vals['Channel'] bookmark = None if channel not in self.__bookmarks: self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( None) bookmark = self.__bookmarks[channel] win32evtlog.EvtUpdateBookmark(bookmark, event) finally: self.__bookmark_lock.release()