Beispiel #1
0
    def GetFormattedEventAsDict( self, render_context, event ):
        vals = win32evtlog.EvtRender( event, win32evtlog.EvtRenderEventValues, Context=render_context )

        result = {}

        event_id = vals[win32evtlog.EvtSystemEventID]
        qualifiers = vals[win32evtlog.EvtSystemQualifiers]

        metadata = None
        try:
            metadata = win32evtlog.EvtOpenPublisherMetadata( vals[win32evtlog.EvtSystemProviderName][0] )
        except:
            pass

        result['Message'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageEvent, '' )

        if vals[win32evtlog.EvtSystemLevel][1] != win32evtlog.EvtVarTypeNull:
            result['Level'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageLevel, vals[win32evtlog.EvtSystemLevel][0] )

        if vals[win32evtlog.EvtSystemOpcode][1] != win32evtlog.EvtVarTypeNull:
            result['Opcode'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageOpcode, vals[win32evtlog.EvtSystemOpcode][0]  )

        if vals[win32evtlog.EvtSystemKeywords][1] != win32evtlog.EvtVarTypeNull:
            result['Keywords'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageKeyword, vals[win32evtlog.EvtSystemKeywords][0]  )

        if vals[win32evtlog.EvtSystemChannel][1] != win32evtlog.EvtVarTypeNull:
            result['Channel'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageChannel, vals[win32evtlog.EvtSystemChannel][0]  )
        result['Task'] = self._FormattedMessage( metadata, event, win32evtlog.EvtFormatMessageTask, ""  )


        self._AddValueIfNotNullType( result, 'ProviderName', vals[win32evtlog.EvtSystemProviderName] )
        self._AddValueIfNotNullType( result, 'ProviderGuid', vals[win32evtlog.EvtSystemProviderGuid] )
        self._AddValueIfNotNullType( result, 'TimeCreated', vals[win32evtlog.EvtSystemTimeCreated] )
        self._AddValueIfNotNullType( result, 'RecordId',  vals[win32evtlog.EvtSystemEventRecordId] )
        self._AddValueIfNotNullType( result, 'ActivityId',  vals[win32evtlog.EvtSystemActivityID] )
        self._AddValueIfNotNullType( result, 'RelatedActivityId',  vals[win32evtlog.EvtSystemRelatedActivityID] )
        self._AddValueIfNotNullType( result, 'ProcessId',  vals[win32evtlog.EvtSystemProcessID] )
        self._AddValueIfNotNullType( result, 'ThreadId',  vals[win32evtlog.EvtSystemThreadID] )
        self._AddValueIfNotNullType( result, 'Computer',  vals[win32evtlog.EvtSystemComputer] )
        self._AddValueIfNotNullType( result, 'UserId',  vals[win32evtlog.EvtSystemUserID] )
        self._AddValueIfNotNullType( result, 'Version',  vals[win32evtlog.EvtSystemVersion] )

        return result
Beispiel #2
0
    def collect_provider(self, event_payload, rendered_event, event_object):
        value, variant = rendered_event[win32evtlog.EvtSystemProviderName]
        if variant == win32evtlog.EvtVarTypeNull:
            return

        event_payload['aggregation_key'] = value
        event_payload['msg_title'] = '{}/{}'.format(self._path, value)

        message = None

        # See https://docs.microsoft.com/en-us/windows/win32/wes/getting-a-provider-s-metadata-
        try:
            # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtopenpublishermetadata
            metadata = win32evtlog.EvtOpenPublisherMetadata(value)
        # Code 2: The system cannot find the file specified.
        except pywintypes.error as e:
            if self._interpret_messages:
                message = self.interpret_message(event_object)
            else:
                self.log_windows_error(e)
        else:  # no cov
            try:
                # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtformatmessage
                # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_format_message_flags
                message = win32evtlog.EvtFormatMessage(
                    metadata, event_object, win32evtlog.EvtFormatMessageEvent)
            # Code 15027: The message resource is present but the message was not found in the message table.
            # Code 15028: The message ID for the desired message could not be found.
            except pywintypes.error as e:
                if self._interpret_messages:
                    message = self.interpret_message(event_object)
                else:
                    self.log_windows_error(e)

        if message is not None:
            message = self.sanitize_message(message.rstrip())

            if self.message_filtered(message):
                return False

            event_payload['msg_text'] = message
Beispiel #3
0
    def GetFormattedEventAsDict(self, render_context, event):
        vals = win32evtlog.EvtRender(event,
                                     win32evtlog.EvtRenderEventValues,
                                     Context=render_context)

        result = {}

        # In the new event log api, EventIds were replaced by an InstanceId.
        # The InstanceID is made by combining the old EventId with any
        # SystemQualifiers associated with the event, to create a new 32bit value
        # with the EventId in the lower 16bits and the SystemQualifiers
        # in the high 16bits.
        event_id_val = vals[win32evtlog.EvtSystemEventID]
        if event_id_val[1] != win32evtlog.EvtVarTypeNull:
            # by default use the event id value as the event id
            event_id = event_id_val[0]
            qualifiers_val = vals[win32evtlog.EvtSystemQualifiers]
            # if we have any system qualifiers for this event
            if qualifiers_val[1] != win32evtlog.EvtVarTypeNull:
                # then combine the event id with the qualifiers to
                # make the full event id.
                event_id = win32api.MAKELONG(event_id, qualifiers_val[0])
            result['EventID'] = event_id

        metadata = None
        try:
            metadata = win32evtlog.EvtOpenPublisherMetadata(
                vals[win32evtlog.EvtSystemProviderName][0])
        except:
            pass

        result['Message'] = self._FormattedMessage(
            metadata, event, win32evtlog.EvtFormatMessageEvent, '')

        if vals[win32evtlog.EvtSystemLevel][1] != win32evtlog.EvtVarTypeNull:
            result['Level'] = self._FormattedMessage(
                metadata, event, win32evtlog.EvtFormatMessageLevel,
                vals[win32evtlog.EvtSystemLevel][0])

        if vals[win32evtlog.EvtSystemOpcode][1] != win32evtlog.EvtVarTypeNull:
            result['Opcode'] = self._FormattedMessage(
                metadata, event, win32evtlog.EvtFormatMessageOpcode,
                vals[win32evtlog.EvtSystemOpcode][0])

        if vals[win32evtlog.
                EvtSystemKeywords][1] != win32evtlog.EvtVarTypeNull:
            result['Keywords'] = self._FormattedMessage(
                metadata, event, win32evtlog.EvtFormatMessageKeyword,
                vals[win32evtlog.EvtSystemKeywords][0])

        if vals[win32evtlog.EvtSystemChannel][1] != win32evtlog.EvtVarTypeNull:
            result['Channel'] = self._FormattedMessage(
                metadata, event, win32evtlog.EvtFormatMessageChannel,
                vals[win32evtlog.EvtSystemChannel][0])
        result['Task'] = self._FormattedMessage(
            metadata, event, win32evtlog.EvtFormatMessageTask, "")

        self._AddValueIfNotNullType(result, 'ProviderName',
                                    vals[win32evtlog.EvtSystemProviderName])
        self._AddValueIfNotNullType(result, 'ProviderGuid',
                                    vals[win32evtlog.EvtSystemProviderGuid])
        self._AddValueIfNotNullType(result, 'TimeCreated',
                                    vals[win32evtlog.EvtSystemTimeCreated])
        self._AddValueIfNotNullType(result, 'RecordId',
                                    vals[win32evtlog.EvtSystemEventRecordId])
        self._AddValueIfNotNullType(result, 'ActivityId',
                                    vals[win32evtlog.EvtSystemActivityID])
        self._AddValueIfNotNullType(
            result, 'RelatedActivityId',
            vals[win32evtlog.EvtSystemRelatedActivityID])
        self._AddValueIfNotNullType(result, 'ProcessId',
                                    vals[win32evtlog.EvtSystemProcessID])
        self._AddValueIfNotNullType(result, 'ThreadId',
                                    vals[win32evtlog.EvtSystemThreadID])
        self._AddValueIfNotNullType(result, 'Computer',
                                    vals[win32evtlog.EvtSystemComputer])
        self._AddValueIfNotNullType(result, 'UserId',
                                    vals[win32evtlog.EvtSystemUserID])
        self._AddValueIfNotNullType(result, 'Version',
                                    vals[win32evtlog.EvtSystemVersion])

        return result
def main():
    path = 'System'
    num_events = 5
    if len(sys.argv) > 2:
        path = sys.argv[1]
        num_events = int(sys.argv[2])
    elif len(sys.argv) > 1:
        path = sys.argv[1]

    query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection)
    events = win32evtlog.EvtNext(query, num_events)
    context = win32evtlog.EvtCreateRenderContext(
        win32evtlog.EvtRenderContextSystem)

    for i, event in enumerate(events, 1):
        result = win32evtlog.EvtRender(event,
                                       win32evtlog.EvtRenderEventValues,
                                       Context=context)

        print(('Event {}'.format(i)))

        level_value, level_variant = result[win32evtlog.EvtSystemLevel]
        if level_variant != win32evtlog.EvtVarTypeNull:
            if level_value == 1:
                print('    Level: CRITICAL')
            elif level_value == 2:
                print('    Level: ERROR')
            elif level_value == 3:
                print('    Level: WARNING')
            elif level_value == 4:
                print('    Level: INFO')
            elif level_value == 5:
                print('    Level: VERBOSE')
            else:
                print('    Level: UNKNOWN')

        time_created_value, time_created_variant = result[
            win32evtlog.EvtSystemTimeCreated]
        if time_created_variant != win32evtlog.EvtVarTypeNull:
            print(('    Timestamp: {}'.format(time_created_value.isoformat())))

        computer_value, computer_variant = result[
            win32evtlog.EvtSystemComputer]
        if computer_variant != win32evtlog.EvtVarTypeNull:
            print(('    FQDN: {}'.format(computer_value)))

        provider_name_value, provider_name_variant = result[
            win32evtlog.EvtSystemProviderName]
        if provider_name_variant != win32evtlog.EvtVarTypeNull:
            print(('    Provider: {}'.format(provider_name_value)))

            try:
                metadata = win32evtlog.EvtOpenPublisherMetadata(
                    provider_name_value)
            # pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.')
            except Exception:
                pass
            else:
                try:
                    message = win32evtlog.EvtFormatMessage(
                        metadata, event, win32evtlog.EvtFormatMessageEvent)
                # pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.')
                except Exception:
                    pass
                else:
                    print(('    Message: {}'.format(message)))
def main():
    path = "System"
    num_events = 5
    if len(sys.argv) > 2:
        path = sys.argv[1]
        num_events = int(sys.argv[2])
    elif len(sys.argv) > 1:
        path = sys.argv[1]

    query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection)
    events = win32evtlog.EvtNext(query, num_events)
    context = win32evtlog.EvtCreateRenderContext(
        win32evtlog.EvtRenderContextSystem)

    for i, event in enumerate(events, 1):
        result = win32evtlog.EvtRender(event,
                                       win32evtlog.EvtRenderEventValues,
                                       Context=context)

        print("Event {}".format(i))

        level_value, level_variant = result[win32evtlog.EvtSystemLevel]
        if level_variant != win32evtlog.EvtVarTypeNull:
            if level_value == 1:
                print("    Level: CRITICAL")
            elif level_value == 2:
                print("    Level: ERROR")
            elif level_value == 3:
                print("    Level: WARNING")
            elif level_value == 4:
                print("    Level: INFO")
            elif level_value == 5:
                print("    Level: VERBOSE")
            else:
                print("    Level: UNKNOWN")

        time_created_value, time_created_variant = result[
            win32evtlog.EvtSystemTimeCreated]
        if time_created_variant != win32evtlog.EvtVarTypeNull:
            print("    Timestamp: {}".format(time_created_value.isoformat()))

        computer_value, computer_variant = result[
            win32evtlog.EvtSystemComputer]
        if computer_variant != win32evtlog.EvtVarTypeNull:
            print("    FQDN: {}".format(computer_value))

        provider_name_value, provider_name_variant = result[
            win32evtlog.EvtSystemProviderName]
        if provider_name_variant != win32evtlog.EvtVarTypeNull:
            print("    Provider: {}".format(provider_name_value))

            try:
                metadata = win32evtlog.EvtOpenPublisherMetadata(
                    provider_name_value)
            # pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.')
            except Exception:
                pass
            else:
                try:
                    message = win32evtlog.EvtFormatMessage(
                        metadata, event, win32evtlog.EvtFormatMessageEvent)
                # pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.')
                except Exception:
                    pass
                else:
                    try:
                        print("    Message: {}".format(message))
                    except UnicodeEncodeError:
                        # Obscure error when run under subprocess.Popen(), presumably due to
                        # not knowing the correct encoding for the console.
                        # > UnicodeEncodeError: \'charmap\' codec can\'t encode character \'\\u200e\' in position 57: character maps to <undefined>\r\n'
                        # Can't reproduce when running manually, so it seems more a subprocess.Popen()
                        # than ours:
                        print(" Failed to decode:", repr(message))