Beispiel #1
0
 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
Beispiel #2
0
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 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
Beispiel #4
0
    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)
Beispiel #5
0
    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 test_channel_existence(channel):
    h = win32event.CreateEvent(None, 0, 0, None)
    try:
        win32evtlog.EvtSubscribe(channel,
                                 win32evtlog.EvtSubscribeToFutureEvents,
                                 SignalEvent=h,
                                 Query='*')
    except pywintypes.error as e:
        return False
    return True
Beispiel #7
0
 def subscribe(self, log_name, query='*'):
     if log_name in self.__subscriptions:
         return True
     try:
         subscription = win32evtlog.EvtSubscribe(
             log_name,
             win32evtlog.EvtSubscribeToFutureEvents,
             Query=query,
             Callback=self.__log_callback,
             Context=log_name)
         self.__subscriptions[log_name] = subscription
     except win32evtlog.error:
         return False
     return True
    def _subscribe_to_events(self):
        """
            Go through all channels, and create an event subscription to that channel.
            If a bookmark exists for a given channel, start the events from that bookmark, otherwise subscribe
            to future events only.
        """

        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()

                error_message = None
                try:
                    handle = win32evtlog.EvtSubscribe(
                        channel,
                        flags,
                        Bookmark=bookmark,
                        Query=query,
                        Callback=event_callback,
                        Context=self,
                        Session=self._session,
                    )
                except Exception as e:
                    handle = None
                    error_message = win32api.FormatMessage(0)

                if handle is None:
                    self._logger.warn(
                        "Error subscribing to channel '%s' - %s"
                        % (channel, error_message)
                    )
                else:
                    self.__eventHandles.append(handle)
Beispiel #9
0
    def add_event_handler(s, task):
        def run_task_with_data(reason, context, event):
            ' Converts event XML to dictionary '
            r'''
			<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
				<System>
					<Provider Name="Microsoft-Windows-DistributedCOM" Guid="{1B562E86-B7AA-4131-BADC-B6F3A001407E}" EventSourceName="DCOM" /> 
					<EventID Qualifiers="0">10010</EventID> 
					<Version>0</Version> 
					<Level>2</Level> 
					<Task>0</Task> 
					<Opcode>0</Opcode> 
					<Keywords>0x8080000000000000</Keywords> 
					<TimeCreated SystemTime="2021-02-10T12:24:20.581005200Z" /> 
					<EventRecordID>729301</EventRecordID> 
					<Correlation /> 
					<Execution ProcessID="952" ThreadID="41804" /> 
					<Channel>System</Channel> 
					<Computer>DB</Computer> 
					<Security UserID="S-1-5-20" /> 
				</System>
				<EventData>
					<Data Name="param1">{AAC1009F-AB33-48F9-9A21-7F5B88426A2E}</Data> 
				</EventData>
			</Event>
			'''
            xml_str = win32evtlog.EvtRender(event,
                                            win32evtlog.EvtRenderEventXml)
            s.run_task(task=task, caller=CALLER_EVENT, data=DataEvent(xml_str))

        try:
            s.event_handlers.append(
                win32evtlog.EvtSubscribe(
                    task['event_log'], win32evtlog.EvtSubscribeToFutureEvents,
                    None, run_task_with_data, None, task['event_xpath'], None,
                    None))
        except:
            msgbox_warning(
                lang.warn_event_format.format(task['task_name_full']))
## 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
Beispiel #11
0
# Demonstrates a "push" subscription with a callback function
import win32evtlog
query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]'


def c(reason, context, evt):
    if reason == win32evtlog.EvtSubscribeActionError:
        print('EvtSubscribeActionError')
    elif reason == win32evtlog.EvtSubscribeActionDeliver:
        print('EvtSubscribeActionDeliver')
    else:
        print(('??? Unknown action ???', reason))
    context.append(win32evtlog.EvtRender(evt, win32evtlog.EvtRenderEventXml))
    return 0

evttext = []
s = win32evtlog.EvtSubscribe(
    'System',
    win32evtlog.EvtSubscribeStartAtOldestRecord,
    Query='*',
    Callback=c,
    Context=evttext)
## Demonstrates a "push" subscription with a callback function
import win32evtlog

query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]'


def c(reason, context, evt):
    if reason == win32evtlog.EvtSubscribeActionError:
        print("EvtSubscribeActionError")
    elif reason == win32evtlog.EvtSubscribeActionDeliver:
        print("EvtSubscribeActionDeliver")
    else:
        print("??? Unknown action ???", reason)
    context.append(win32evtlog.EvtRender(evt, win32evtlog.EvtRenderEventXml))
    return 0


evttext = []
s = win32evtlog.EvtSubscribe(
    "System",
    win32evtlog.EvtSubscribeStartAtOldestRecord,
    Query="*",
    Callback=c,
    Context=evttext,
)
Beispiel #13
0
                         win32evtlog.EvtRpcLoginAuthDefault)
evtSession = win32evtlog.EvtOpenSession(evtSessionCredentials,
                                        win32evtlog.EvtRpcLogin, 0, 0)

XPathQuery = "*[System[({})]".format(
    ' or '.join("EventID=" + str(x) for x in eventIDs)
)  # The XPath-styled query to tell the domain controller which events to return


#evt1: int specifying why the function was called | evt2: context object (5th parameter in EvtSubscribe) | evt3: event content
def eventTriggered(evt1, evt2, evt3):
    print("Triggered")
    print(evt1)
    print(evt2)
    print(win32evtlog.EvtRender(evt3, win32evtlog.EvtRenderEventXml))
    win32event.PulseEvent(evtHandle)


evtHandle = win32event.CreateEvent(None, 0, 0, None)
x = win32evtlog.EvtSubscribe(eventlog, win32evtlog.EvtSubscribeToFutureEvents,
                             None, eventTriggered, None, XPathQuery, None,
                             None)
while True:
    if win32event.WaitForSingleObject(
            evtHandle, 600000
    ) == win32event.WAIT_OBJECT_0:  # Not really necessary to have this or PulseEvent. Probably better to do everything in eventTriggered.
        # print(win32evtlog.EvtRender(x, win32evtlog.EvtRenderEventXml))
        pass
    else:
        print('timeout')