Ejemplo n.º 1
0
def BackupClearLog(logType):
    datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
    fileExists = 1
    retry = 0
    while fileExists:
        if retry == 0:
            index = ""
        else:
            index = "-%d" % retry
        try:
            fname = os.path.join(
                win32api.GetTempPath(),
                "%s%s-%s" % (datePrefix, index, logType) + ".evt")
            os.stat(fname)
        except os.error:
            fileExists = 0
        retry = retry + 1
    # OK - have unique file name.
    try:
        hlog = win32evtlog.OpenEventLog(None, logType)
    except win32evtlogutil.error as details:
        print("Could not open the event log", details)
        return
    try:
        if win32evtlog.GetNumberOfEventLogRecords(hlog) == 0:
            print("No records in event log %s - not backed up" % logType)
            return
        win32evtlog.ClearEventLog(hlog, fname)
        print("Backed up %s log to %s" % (logType, fname))
    finally:
        win32evtlog.CloseEventLog(hlog)
Ejemplo n.º 2
0
def get_event_logs(server, name, filters):
    handle = win32evtlog.OpenEventLog(server, name)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    logs = []

    try:
        logged_after = filters['logged_after']
        logged_after = datetime.datetime.now() - logged_after
    except KeyError:
        logged_after = datetime.datetime.now() - datetime.timedelta(days=1)

    try:
        while True:
            events = win32evtlog.ReadEventLog(handle, flags, 0)
            if events:
                for event in events:
                    time_generated = datetime_from_event_date(event.TimeGenerated)
                    if time_generated < logged_after:
                        raise StopIteration
                    elif is_interesting_event(event, name, filters):
                        safe_log = normalize_event(event, name)
                        logs.append(safe_log)
            else:
                raise StopIteration
    except StopIteration:
        pass
    finally:
        win32evtlog.CloseEventLog(handle)
    return logs
def get_event_log(server, log_type='system'):
    log_handle = win32evtlog.OpenEventLog(server, log_type)

    total_num_records = win32evtlog.GetNumberOfEventLogRecords(log_handle)

    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ

    print "There are %d records" % total_num_records
    events = 1
    while events:
        events = win32evtlog.ReadEventLog(log_handle, flags, 0)
        for event in events:
            if is_common_event_id(event.EventID):
                print event.EventID
                print event.EventCategory
                print event.TimeGenerated.Format()
                # print event.TimeWritten  # <type 'time'>
                print event.EventType  # win32evtlog.EVENTLOG_ERROR_TYPE,
                print event.ComputerName
                print event.SourceName
                print win32evtlogutil.SafeFormatMessage(event, log_type)  # Event Description
                # print event.StringInserts
                print event.Sid
                if event.Sid is not None:
                    try:
                        domain, user, typ = win32security.LookupAccountSid(server, event.Sid)
                        sidDesc = "%s/%s" % (domain, user)
                    except win32security.error:  # from pywintypes import error
                        sidDesc = str(event.Sid)
                    user_desc = "Event associated with user %s" % (sidDesc,)
                else:
                    user_desc = None
                print user_desc

    win32evtlog.CloseEventLog(log_handle)
Ejemplo n.º 4
0
def readEventLog(server, log_type):
    # Reads the log_type (e.g. "Application" or "System" from the Windows event viewer on the specified server

    try:
        # Open the log file and sort array on Event ID's
        log_handle = win32evtlog.OpenEventLog(server, log_type)
        flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        total = win32evtlog.GetNumberOfEventLogRecords(log_handle)

        print("Scanning through {} events on {} in {}".format(
            total, server, log_type))

        # As long as there are events, keep reading
        readEvent_count = 1
        readEvents = 1
        events = []

        while readEvents:
            readEvents = win32evtlog.ReadEventLog(log_handle, flags, 1)

            for event in readEvents:
                events.append(event)
                readEvent_count += 1

        win32evtlog.CloseEventLog(log_handle)
        return events

    except:
        print("I can't read yar bastard")

        try:
            print(traceback.print_exc(sys.exc_info()))
        except:
            print("Exception whilst printing traceback")
Ejemplo n.º 5
0
    def read_and_parse(self):
        flag = False
        while True:
            if flag:
                break
            self.hand = win32evtlog.OpenEventLog(self.server, self.logtype)
            events = win32evtlog.ReadEventLog(self.hand, self.flags, 0)
            w_logs = []
            if events:
                for event in events:
                    if event.TimeGenerated > self.last_log_timestamp:
                        msg_data = event.StringInserts
                        if msg_data:
                            msg = ' '.join(msg_data)
                        else:
                            msg = ''
                        w_log = WindowsLog(str(event.TimeGenerated),
                                           SeverityLevel(event.EventType).name,
                                           event.EventID, event.ComputerName,
                                           event.SourceName, msg)
                        print(w_log.format_json())
                        w_logs.append(w_log.format_json())
                        self.last_log_timestamp = event.TimeGenerated
                    else:
                        flag = True

        win32evtlog.CloseEventLog(self.hand)

        return w_logs
Ejemplo n.º 6
0
def ReadLog(computer, logType="Application", dumpEachRecord = 0):
    # read the entire log back.
    h=win32evtlog.OpenEventLog(computer, logType)
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
#       print "There are %d records" % numRecords

    num=0
    while 1:
        objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        for object in objects:
            # get it for testing purposes, but dont print it.
            msg = SafeFormatMessage(object, logType).encode("mbcs")
            if object.Sid is not None:
                try:
                    domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
                    sidDesc = "%s/%s" % (domain, user)
                except win32security.error:
                    sidDesc = str(object.Sid)
                user_desc = "Event associated with user %s" % (sidDesc,)
            else:
                user_desc = None
            if dumpEachRecord:
                if user_desc:
                    print user_desc
                print msg
        num = num + len(objects)

    if numRecords == num:
        print "Successfully read all", numRecords, "records"
    else:
        print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
        print "(Note that some other app may have written records while we were running!)"
    win32evtlog.CloseEventLog(h)
Ejemplo n.º 7
0
def clean_event_logs():
    lognames = ['Application', 'Security', 'System']
    machine = None
    for logname in lognames:
        h = win32evtlog.OpenEventLog(machine, logname)
        win32evtlog.ClearEventLog(h, None)
        win32evtlog.CloseEventLog(h)
Ejemplo n.º 8
0
def event_logs(server="localhost", source="System"):
    # type: (str, str) -> Iterator[dict]
    """
	EventType: severity level

	EVENTLOG_ERROR_TYPE 0x0001
	EVENTLOG_WARNING_TYPE 0x0002
	EVENTLOG_INFORMATION_TYPE 0x0004
	EVENTLOG_AUDIT_SUCCESS 0x0008
	EVENTLOG_AUDIT_FAILURE 0x0010

	EventID: same for same class of messages, stringinserts are provides to template belonging to eventid

	"""

    fields = {
        "Reserved", "RecordNumber", "TimeGenerated", "TimeWritten", "EventID",
        "EventType", "EventCategory", "ReservedFlags", "ClosingRecordNumber",
        "SourceName", "StringInserts", "Sid", "Data", "ComputerName"
    }
    fields = {
        "Reserved", "RecordNumber", "TimeGenerated", "TimeWritten", "EventID",
        "EventType", "EventCategory", "ReservedFlags", "ClosingRecordNumber",
        "SourceName", "StringInserts", "ComputerName"
    }

    # missing: "Sid", "Data"

    handle = win32evtlog.OpenEventLog(server, source)
    flags = win32evtlog.EVENTLOG_SEQUENTIAL_READ | win32evtlog.EVENTLOG_FORWARDS_READ

    logger.debug("Preparing to read {} events".format(
        win32evtlog.GetNumberOfEventLogRecords(handle)))

    try:
        while True:
            events = win32evtlog.ReadEventLog(handle, flags, 0)
            if events:
                for event in events:
                    ret = {f: getattr(event, f) for f in fields}
                    # does that work for different time zones?
                    ret["TimeGenerated"] = datetime.fromtimestamp(
                        event.TimeGenerated.timestamp())
                    ret["TimeWritten"] = datetime.fromtimestamp(
                        event.TimeWritten.timestamp())
                    if ret["StringInserts"]:
                        ret["StringInserts"] = ", ".join(
                            ret["StringInserts"]).replace("\r\n", "\n")
                    if not ret["StringInserts"]:
                        ret["StringInserts"] = None
                    ret["EventID"] = winerror.HRESULT_CODE(ret["EventID"])
                    #print(ret)
                    yield ret
            else:
                break
    finally:
        win32evtlog.CloseEventLog(handle)
Ejemplo n.º 9
0
def _close_event_handler(handler):
    '''
    Will close the event handler.

    handler
        PyHANDLE
    '''

    # TODO: downgrade windows token
    win32evtlog.CloseEventLog(handler)
Ejemplo n.º 10
0
def ReadLog(computer, logType="Application", dumpEachRecord=0):
    # read the entire log back.
    h = win32evtlog.OpenEventLog(computer, logType)
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
    #       print "There are %d records" % numRecords

    num = 0
    while 1:
        objects = win32evtlog.ReadEventLog(
            h,
            win32evtlog.EVENTLOG_BACKWARDS_READ
            | win32evtlog.EVENTLOG_SEQUENTIAL_READ,
            0,
        )
        if not objects:
            break
        for object in objects:
            # get it for testing purposes, but dont print it.
            msg = win32evtlogutil.SafeFormatMessage(object, logType)
            if object.Sid is not None:
                try:
                    domain, user, typ = win32security.LookupAccountSid(
                        computer, object.Sid)
                    sidDesc = "%s/%s" % (domain, user)
                except win32security.error:
                    sidDesc = str(object.Sid)
                user_desc = "Event associated with user %s" % (sidDesc, )
            else:
                user_desc = None
            if dumpEachRecord:
                print("Event record from %r generated at %s" %
                      (object.SourceName, object.TimeGenerated.Format()))
                if user_desc:
                    print(user_desc)
                try:
                    print(msg)
                except UnicodeError:
                    print(
                        "(unicode error printing message: repr() follows...)")
                    print(repr(msg))

        num = num + len(objects)

    if numRecords == num:
        print("Successfully read all", numRecords, "records")
    else:
        print("Couldn't get all records - reported %d, but found %d" %
              (numRecords, num))
        print(
            "(Note that some other app may have written records while we were running!)"
        )
    win32evtlog.CloseEventLog(h)
Ejemplo n.º 11
0
def read_events(date_from):
    all_events = []
    event_list = []
    events_from_date = []
    event_list_from_date = []
    event_no = 0
    while 1:
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        if events:
            for event in events:
                if event.EventID in event_dictionary:
                    data = event.StringInserts
                    computer = event.ComputerName
                    message = event_dictionary.get(event.EventID)
                    event_time = str(event.TimeGenerated)
                    user = ''

                    if (event.EventID == 4624
                            or event.EventID == 4625) and username in data[5]:
                        user = data[5]
                        message = message % user
                    elif event.EventID == 4634 and username in data[1]:
                        user = data[1]
                        message = message % user
                    elif event.EventID == 4608:
                        user = "******"
                    elif (event.EventID == 4720 or event.EventID == 4725 or event.EventID == 4726 \
                            or event.EventID == 4722 or event.EventID == 4740 or event.EventID == 4767) and username\
                            in data[4]:
                        user = data[4]
                        account_name = data[0]
                        message = message % account_name

                    if user in (username, 'N/A'):
                        event_list.append(event.EventID)
                        single_row = [
                            event_time, event.EventID, message, user,
                            'Windows Security Event Log', computer
                        ]
                        all_events.append(single_row)

                        if event_time > date_from:
                            events_from_date.append(single_row)
                            event_list_from_date.append(event.EventID)
                event_no += 1
                if event_no >= total:
                    print(
                        "Logon/logoff data gathered from Windows Security event log."
                    )
                    win32evtlog.CloseEventLog(hand)
                    print("number of processed records: " + str(event_no))
                    return all_events, event_list, events_from_date, event_list_from_date
Ejemplo n.º 12
0
def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None):
    if readFlags is None:
        readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ

    h=win32evtlog.OpenEventLog(machineName, logName)
    try:
        while 1:
            objects = win32evtlog.ReadEventLog(h, readFlags, 0)
            if not objects:
                break
            map(lambda item, feeder = feeder: feeder(*(item,)), objects)
    finally:
        win32evtlog.CloseEventLog(h)
Ejemplo n.º 13
0
def yield_logs(computer=None, log_name=LOG_NAME):
    hLog = win32evtlog.OpenEventLog(computer, log_name)
    try:
        while True:
            entries = win32evtlog.ReadEventLog(
                hLog, win32evtlog.EVENTLOG_BACKWARDS_READ
                | win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
            if entries:
                for entry in entries:
                    yield entry
            else:
                break
    finally:
        win32evtlog.CloseEventLog(hLog)
Ejemplo n.º 14
0
 def test_event_log_clear_with_save(self):
     log_name = "Internet Explorer"
     source_name = "_winsys-%s" % uuid.uuid1()
     source = event_logs.EventSource.create(source_name, log_name)
     log = event_logs.event_log(log_name)
     hLog = win32evtlog.OpenEventLog(None, log_name)
     try:
         log.log_event(source, message="hello")
         self.assertNotEquals(win32evtlog.GetNumberOfEventLogRecords(hLog),
                              0)
         log.clear()
         self.assertEqual(win32evtlog.GetNumberOfEventLogRecords(hLog), 0)
     finally:
         win32evtlog.CloseEventLog(hLog)
         source.delete()
Ejemplo n.º 15
0
def ParseEvents(eventtype, server):

    try:
        hand = win32evtlog.OpenEventLog(server, eventtype)
    except pywintypes.error as e:
        SetColor(FOREGROUND_RED | FOREGROUND_INTENSITY)
        print e[2]
        SetColor(FOREGROUND_WHITE)
        os._exit(0)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    events = 1
    count = 0
    result = []
    results = result.append
    while events:
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        if events:
            for event in events:
                count += 1
                time = "date_time= %s" % str(event.TimeGenerated)
                cat = "type= %s" % str(event.SourceName)
                eventID = "eventid= %s" % str(event.EventID & 0x1FFFFFFF)
                strings = "data= %s" % str(event.StringInserts).replace(
                    "\\\\", "\\").replace("u'", "'").replace("%%", "")
                results((time, cat, eventID, strings))
                bar_len = 55
                filled_len = int(round(bar_len * count / float(total)))
                percents = round(100.0 * count / float(total), 1)
                bar = '=' * filled_len + '-' * (bar_len - filled_len)
                sys.stdout.write('[%s] %s%s %s/%s \r' %
                                 (bar, percents, '%', count, total))
                sys.stdout.flush()
            yield result

    if total == count:
        SetColor(FOREGROUND_AQUA | FOREGROUND_INTENSITY)
        print
        print "Successfully read all", total, "records"
        print
    else:
        SetColor(FOREGROUND_RED | FOREGROUND_INTENSITY)
        print
        print "Couldn't get all records - reported %d, but found %d" % (total,
                                                                        count)
        print "(Note that some other app may have written records while we were running!)"
        print
    win32evtlog.CloseEventLog(hand)
Ejemplo n.º 16
0
	def find_event_log_entry(self):
		handle = win32evtlog.OpenEventLog('localhost', 'Siemplify')
		flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ

		keep_running = True
		found_event = None
		while keep_running:
			events = win32evtlog.ReadEventLog(handle, flags, 0)
			for event in events:
				if SERVICE_START_EVENTID == event.EventID:
					if WORKING_SERVICE_INDICATOR in event.StringInserts[0]:
						print event.SourceName
						found_event = event
						keep_running = False

		win32evtlog.CloseEventLog(handle)
		return found_event
Ejemplo n.º 17
0
def readEventLog(server, log_type):
    '''
    Reads the log_type (e.g., "Application" or "System") Windows events from the
    specified server.
    '''
    begin_sec = time.time()
    begin_time = time.strftime('%H:%M:%S  ', time.localtime(begin_sec))

    seconds_per_hour = 60 * 60
    how_many_seconds_back_to_search = seconds_per_hour * 1

    gathered_events = []

    try:
        log_handle = win32evtlog.OpenEventLog(server, log_type)

        total = win32evtlog.GetNumberOfEventLogRecords(log_handle)
        print("Scanning through {} events on {} in {}".format(
            total, server, log_type))

        flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ

        event_count = 0
        events = 1
        while events:
            events = win32evtlog.ReadEventLog(log_handle, flags, 0)
            seconds = begin_sec
            for event in events:
                the_time = event.TimeGenerated.Format()
                seconds = 1
                if seconds < begin_sec - how_many_seconds_back_to_search: break

                if event.EventType == win32con.EVENTLOG_ERROR_TYPE:
                    event_count += 1
                    gathered_events.append(event)
            if seconds < begin_sec - how_many_seconds_back_to_search:
                break  # get out of while loop as well

        win32evtlog.CloseEventLog(log_handle)
    except:
        try:
            print(traceback.print_exc(sys.exc_info()))
        except:
            print('Exception while printing traceback')

    return gathered_events
Ejemplo n.º 18
0
def main(computer='.', logtype='System', interval=480):
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|\
            win32evtlog.EVENTLOG_SEQUENTIAL_READ
    evt_dict = {
        win32con.EVENTLOG_AUDIT_FAILURE: '审核失败事件',
        win32con.EVENTLOG_AUDIT_SUCCESS: '审核成功事件',
        win32con.EVENTLOG_INFORMATION_TYPE: '通知事件',
        win32con.EVENTLOG_WARNING_TYPE: '警告事件',
        win32con.EVENTLOG_ERROR_TYPE: '错误事件'
    }
    begin_sec = time.time()
    begin_time = time.strftime('%H:%M:%S', time.localtime(begin_sec))
    try:
        hand = win32evtlog.OpenEventLog(computer, logtype)  #打开日志
    except:
        print('无法打开"{0}"服务器上的"{1}"日志'.format(computer, logtype))
        return
    print(
        logtype, ' events found in the last {0} hours before {1}'.format(
            interval / 60 / 60, begin_time))

    events = 1
    while events:
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        for ev_obj in events:
            try:
                the_time = ev_obj.TimeGenerated.Format('%D %H:%M:%S')
                seconds = date2sec(the_time)
                if seconds < begin_sec - interval:  #只查看指定时间段内的日志
                    break
                computer = ev_obj.ComputerName
                cat = str(ev_obj.EventCategory)
                src = str(ev_obj.SourceName)
                record = str(ev_obj.RecordNumber)
                evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID))
                evt_type = evt_dict[ev_obj.EventType]
                msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype)
                print(':'.join((the_time, computer, src, cat, record, evt_id,
                                evt_type, msg)))
                print('=' * 20)
                if seconds < begin_sec - interval:
                    break
            except:
                pass
    win32evtlog.CloseEventLog(hand)
Ejemplo n.º 19
0
def isLocked():
    hand = win32evtlog.OpenEventLog(None, "Security")
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    records = win32evtlog.ReadEventLog(hand, flags, 0)
    win32evtlog.CloseEventLog(hand)

    # Find latest lock or unlock event.
    for record in records:
        eid = record.EventID

        # Unlocked.
        if (eid == 4801):
            return False
        # Locked.
        elif (eid == 4800):
            return True

    # Assume state hasn't changed.
    return tester.state
Ejemplo n.º 20
0
 def readEventLog(self, server, log_type, eventArray):
     '''
     Reads the log_type (e.g., "Application" or "System") Windows events from the
     specified server.
     '''
     try:
         """Open Log File and sort array on Event ID"""
         log_handle = win32evtlog.OpenEventLog(server, log_type)
         flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
         total = win32evtlog.GetNumberOfEventLogRecords(log_handle)
         try:
             eventArray.sort(
                 key=lambda x:
                 (x.EventType or 0, x.EventID or 0, x.Sid or 0, x.SourceName
                  or '', x.StringInserts or '', x.EventCategory or 0, x.Data
                  or '', x.ComputerName or ''),
                 reverse=True)
         except Exception as e:
             print(e)
             try:
                 logger.info(traceback.print_exc(sys.exc_info()))
             except:
                 logger.info('Exception sort went wrong')
         logger.info("Scanning through {} events on {} in {}".format(
             total, server, log_type))
         """As long as there are events keep reading"""
         readEvent_count = 0
         readEvents = 1
         while readEvents:
             readEvents = win32evtlog.ReadEventLog(log_handle, flags, 0)
             for readEvent in readEvents:
                 self.compareLogRecordWithList(eventArray, readEvent)
                 readEvent_count += 1
         """"Close Log File"""
         logger.info("Scanned through {} events on {} in {}".format(
             readEvent_count, server, log_type))
         win32evtlog.CloseEventLog(log_handle)
     except:
         logger.info("I cant read yar bastard")
         try:
             logger.info(traceback.print_exc(sys.exc_info()))
         except:
             logger.info('Exception while printing traceback')
Ejemplo n.º 21
0
    def read_log(self):
        print("Opening : " + self.SourceName)

        # http://timgolden.me.uk/pywin32-docs/win32evtlog__OpenEventLog_meth.html
        # https://docs.microsoft.com/en-us/windows/win32/eventlog/querying-for-event-source-messages
        # EventLog keys: https://docs.microsoft.com/en-us/windows/desktop/eventlog/eventlog-key
        #  reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog

        log_handle = win32evtlog.OpenEventLog(self.MachineName,
                                              self.SourceName)

        if log_handle is None:
            return

        # Path : str
        #     Event log name or Path of an export file
        # Flags : int
        #    EvtOpenChannelPath (1) or EvtOpenFilePath (2)
        # Session=None : PyEVT_HANDLE
        #    Handle to a remote session (see win32evtlog::EvtOpenSession), or None for local machine.
        # win32evtlog.EvtOpenLog('ForwardedEvents', 1 , None)

        flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        total = win32evtlog.GetNumberOfEventLogRecords(log_handle)
        print("Total: %d" % total)

        events = 1
        while events:
            # https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readeventloga
            events = win32evtlog.ReadEventLog(log_handle, flags, 0)
            # http://timgolden.me.uk/pywin32-docs/PyEventLogRecord.html
            for event in events:
                if not event:
                    break

                print("%s: %s %d" % (event.TimeWritten.Format(),
                                     event.SourceName, event.EventID))
                if event.StringInserts:
                    for string_insert in event.StringInserts:
                        print('\t' + string_insert)
                    print('')

        win32evtlog.CloseEventLog(log_handle)
Ejemplo n.º 22
0
def get_eventlogs(source_name="Microsoft-Windows-PrintService/Operational",
                  buf_size=EVTLOG_READ_BUF_LEN_MAX,
                  backwards=True):
    ret = list()
    evt_log = win32evtlog.OpenEventLog(None, source_name)
    read_flags = win32evtlog.EVENTLOG_SEQUENTIAL_READ
    if backwards:
        read_flags |= win32evtlog.EVENTLOG_BACKWARDS_READ
    else:
        read_flags |= win32evtlog.EVENTLOG_FORWARDS_READ
    offset = 0
    eventlog_records = win32evtlog.ReadEventLog(evt_log, read_flags, offset,
                                                buf_size)
    while eventlog_records:
        ret.extend(eventlog_records)
        offset += len(eventlog_records)
        eventlog_records = win32evtlog.ReadEventLog(evt_log, read_flags,
                                                    offset, buf_size)
    win32evtlog.CloseEventLog(evt_log)
    return ret
Ejemplo n.º 23
0
def getLastExecuted(computer, exeList):
    logType = "Security"
    query = "A new process has been created."
    eventLog = win32evtlog.OpenEventLog(
        computer, logType)  # Object consisting of all records in requested log

    while True:
        # Magic code BEGINS
        objects = win32evtlog.ReadEventLog(
            eventLog, win32evtlog.EVENTLOG_BACKWARDS_READ
            | win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        # Magic code ENDS
        for object in objects:
            # get it for testing purposes, but don't print it. - Not written by me. No idea what this does
            record = win32evtlogutil.SafeFormatMessage(object, logType)
            try:
                recordLines = record.splitlines()
                if recordLines[0] == query:
                    for i in range(len(recordLines)):
                        if "New Process Name:" in recordLines[i]:
                            for j in range(len(exeList)):
                                if exeList[j].path in recordLines[i]:
                                    if not exeList[
                                            j].checked:  # record list is sorted newest to oldest, so we check to see if the processes last launch time has already been recorded
                                        exeList[j].checked = True
                                        exeList[j].lastLaunch = timeslation(
                                            object.TimeGenerated.Format()
                                        )  # returns a String of the timestamp of the record
                                    break
                            break

            except UnicodeError:
                print("(unicode error printing message: repr() follows...)")
                print(repr(record))

    win32evtlog.CloseEventLog(eventLog)
    return exeList
Ejemplo n.º 24
0
def main():
    server = None  # "localhost" # name of the target computer to get event logs
    source_type = "System"  # "Application" # "Security"
    h_log = win32evtlog.OpenEventLog(server, source_type)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(h_log)
    print(total)
    h_evt = win32event.CreateEvent(None, 1, 0, "evt0")
    win32evtlog.NotifyChangeEventLog(h_log, h_evt)
    print(
        "Waiting for changes in the '{:s}' event log. Press a key to exit...".
        format(source_type))
    while not msvcrt.kbhit():
        wait_result = win32event.WaitForSingleObject(h_evt, 500)
        if wait_result == win32con.WAIT_OBJECT_0:
            print("The '{:s}' event log has been modified".format(source_type))
            # Any processing goes here
        elif wait_result == win32con.WAIT_ABANDONED:
            print("Abandoned")

    win32api.CloseHandle(h_evt)
    win32evtlog.CloseEventLog(h_log)
Ejemplo n.º 25
0
def run(parameters):
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    evt_dict = {
        win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE',
        win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS',
        win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE',
        win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE',
        win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE'
    }
    computer = ''
    begin_sec = time.time()
    time_back = int(parameters.split(",")[1]) * 3600
    logtype = parameters.split(",")[0]
    hand = win32evtlog.OpenEventLog(computer, logtype)
    count = 0
    try:
        events = 1
        while events:
            events = win32evtlog.ReadEventLog(hand, flags, 0)
            for ev_obj in events:
                #check if the event is recent enough
                #only want data from last 8hrs
                the_time = ev_obj.TimeGenerated.Format()
                seconds = date2sec(the_time)
                if seconds < begin_sec - time_back: break
                #data is recent enough, so print it out
                evt_type = str(evt_dict[ev_obj.EventType])
                if evt_type == "EVENTLOG_ERROR_TYPE":
                    count += 1
                elif evt_type == "EVENTLOG_WARNING_TYPE":
                    count += 1
            if seconds < begin_sec - time_back:
                break  #get out of while loop as well
        win32evtlog.CloseEventLog(hand)
        return count
    except:
        print traceback.print_exc(sys.exc_info())
        return "failed"
Ejemplo n.º 26
0
def main():
    """
    Listens to new Security events on the Domain Controller (localhost).
    For every new logon, the DC will view the latest events of the remote computer trying to logon.
    If there is an event that matches an attack description, quarintine the computer, and disable both the logged on user the the attacked user.

    Return Value (NoneType): None
    """

    log_handle = win32evtlog.OpenEventLog(SERVER, SOURCE_TYPE) # Opens the source_type log from the server
    evt_handle = win32event.CreateEvent(EMPTY_EVENT_ATTRIBUTES, EMPTY_EVENT_MANUAL_STATE, EMPTY_EVENT_INITIAL_STATE, EMPTY_EVENT_NAME) # Creates an empty event
    win32evtlog.NotifyChangeEventLog(log_handle, evt_handle) # Notify changes in h_evt foreach change in h_log
    logger.info(f"Waiting for changes in the '{SOURCE_TYPE}' event log...")
    
    while True:
        wait_result = win32event.WaitForSingleObject(evt_handle, EVT_WAIT_TIME) # Waits for a new object in h_evt
        if wait_result == win32con.WAIT_OBJECT_0: # If there is a new object
            handle_new_event()
                
        elif wait_result == win32con.WAIT_ABANDONED: 
            logger.info("Abandoned")
    win32api.CloseHandle(evt_handle) # Close the event handles
    win32evtlog.CloseEventLog(log_handle) # Close the log file
Ejemplo n.º 27
0
def ReadLog(record_old):
    result = '主机名称:' + sysname.hostname + ' 主机IP:' + get_local_ip(
    ) + ' 登陆失败远端IP:' + get_remote_ip()
    computer = None
    # 查询的日志为系统Security日志
    logType = "Security"
    # 进行日志的读取
    h = win32evtlog.OpenEventLog(computer, logType)
    # 判断是否距离上次查询产生了新日志
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
    new = numRecords - record_old
    # 循环读取新日志,直到全部日志解析完成
    while 1:
        objects = win32evtlog.ReadEventLog(
            h, win32evtlog.EVENTLOG_BACKWARDS_READ
            | win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if new == 0:
            break
        for object in objects:
            if new != 0:
                # 4525为Windows系统用户登陆失败日志ID
                if object.EventID == 4625:  # ==4625
                    temp = str(result)
                    temp = temp + str(object.TimeWritten) + ' ' + str(
                        object.Sid)
                    data = {}
                    data['level'] = '1'
                    data['type'] = '用户事件'
                    data['detail'] = '登陆失败'
                    data['msg'] = temp
                    db.prt_error(data)
                new = new - 1
            else:
                break
    win32evtlog.CloseEventLog(h)
    return numRecords
Ejemplo n.º 28
0
def clearEvents():
	elog = win32evtlog.OpenEventLog(None, "Application")
	win32evtlog.ClearEventLog(elog, None)
	win32evtlog.CloseEventLog(elog)
Ejemplo n.º 29
0
def scan_one_audit_log(path_event_log, backup_flag=True):
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    list_id = [4656, 4663, 4660, 4659]
    try:
        if backup_flag:
            handle = win32evtlog.OpenBackupEventLog(None, path_event_log)
        else:
            handle = win32evtlog.OpenEventLog(None, "Security")

        num_records = win32evtlog.GetNumberOfEventLogRecords(handle)
        total = 0

        pending_delete = {}
        alert_dict = {}
        events = 1  # Object
        while events:
            events = win32evtlog.ReadEventLog(handle, flags, 0)
            for event in events:
                event_category = event.EventCategory
                # ID of event
                event_id = winerror.HRESULT_CODE(event.EventID)
                # Category: File System
                if event_category == 12800 and filter_id(event_id, list_id):
                    # Time generated event
                    event_time = event.TimeGenerated.strftime(
                        '%Y-%m-%d %H:%M:%S')
                    event_computer = str(event.ComputerName)
                    event_user = event.StringInserts[1]
                    event_object = event.StringInserts[6]

                    alert_dict['time'] = event_time
                    alert_dict['user'] = event_user
                    alert_dict['domain'] = event_computer
                    alert_dict['resource'] = event_object

                    # A handle was requested.
                    if event_id == 4656 and has_key(event_object,
                                                    pending_delete):
                        # The file was not deleted -> created/modified
                        pending_delete[event_object]['alive'] = True
                    # Event 4663 = object access.
                    elif event_id == 4663:
                        event_access_mask = event.StringInserts[9]
                        # 0x10000 = Delete, but this can mean different things - delete, overwrite, rename, move.
                        if event_access_mask == '0x10000' and not is_contain_str(
                                "RECYCLE.BIN", event_object):
                            # Ignore metadata files in the recycle bin.
                            if has_key(event_object, pending_delete):
                                # Is it already in the list?  If so, kick it out and replace it.
                                # The most recent handle is used to track a moved file.
                                del pending_delete[event_object]
                            # Record the filename, username, handle ID, and time.
                            pending_delete[event_object] = {}
                            pending_delete[event_object]['user'] = event_user
                            pending_delete[event_object][
                                'handle_id'] = event.StringInserts[7]
                            pending_delete[event_object][
                                'time_created'] = event_time
                            pending_delete[event_object]['alive'] = False
                            pending_delete[event_object]['confirmed'] = False
                        # 0x2 = is a classic "object was modified" signal.
                        if event_access_mask == '0x2' and not is_contain_str(
                                "RECYCLE.BIN", event_object):
                            # Generate report
                            alert_dict['action'] = ADD_FILE_ACTION_MSG
                            alert_dict['note'] = '0x2'
                            print(
                                "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                % (event_time, event_user, event_computer,
                                   ADD_FILE_ACTION_MSG, event_object, "0x2"))
                            insert_alert_monitor(alert_dict)
                            # The file was not actually deleted, so remove it from this array.
                            try:
                                del pending_delete[event_object]
                            except (Exception, ValueError):
                                continue
                        # A 4663 event with 0x80 (Read Attributes) is logged
                        # with the same handle ID when files/folders are moved or renamed.
                        if event_access_mask == '0x80':
                            for key in pending_delete.keys():
                                # If the Handle & User match...and the object wasn't deleted...
                                # figure out whether it was moved or renamed.
                                if pending_delete[key]['handle_id'] == event.StringInserts[7] \
                                        and pending_delete[key]['user'] == event_user \
                                        and event_object != key \
                                        and not pending_delete[key]['confirmed']:
                                    # Files moved to a different folder (same filename, different folder)
                                    if get_file_name(event_object
                                                     ) == get_file_name(key):
                                        alert_dict[
                                            'action'] = MOVE_FILE_ACTION_MSG
                                        alert_dict['note'] = '0x2'
                                        print(
                                            "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                            % (event_time, event_user,
                                               event_computer,
                                               MOVE_FILE_ACTION_MSG,
                                               event_object, "0x2"))
                                        insert_alert_monitor(alert_dict)
                                        del pending_delete[key]
                                    # Files moved into the recycle bin
                                    elif is_contain_str(
                                            'RECYCLE.BIN', event_object):
                                        alert_dict[
                                            'action'] = RECYCLE_FILE_ACTION_MSG
                                        alert_dict['note'] = '0x2'
                                        print(
                                            "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                            % (event_time, event_user,
                                               event_computer,
                                               RECYCLE_FILE_ACTION_MSG,
                                               event_object, "0x2"))
                                        insert_alert_monitor(alert_dict)
                                        del pending_delete[key]
                                    # Files moved out of the recycle bin
                                    elif is_contain_str('RECYCLE.BIN', key):
                                        alert_dict[
                                            'action'] = RESTORE_FILE_ACTION_MSG
                                        alert_dict['note'] = '0x2'
                                        print(
                                            "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                            % (event_time, event_user,
                                               event_computer,
                                               RESTORE_FILE_ACTION_MSG,
                                               event_object, "0x2"))
                                        insert_alert_monitor(alert_dict)
                                        del pending_delete[key]
                                    # Created / renamed files
                                    elif get_folder_name(
                                            event_object) == get_folder_name(
                                                key):
                                        if get_file_name(key) == "New Folder":
                                            alert_dict[
                                                'action'] = ADD_FILE_ACTION_MSG
                                            alert_dict['note'] = ''
                                            print(
                                                "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                                % (event_time, event_user,
                                                   event_computer,
                                                   ADD_FILE_ACTION_MSG,
                                                   event_object, ""))
                                        else:
                                            alert_dict[
                                                'action'] = RENAME_FILE_ACTION_MSG
                                            alert_dict['note'] = ''
                                            print(
                                                "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                                                % (event_time, event_user,
                                                   event_computer,
                                                   RENAME_FILE_ACTION_MSG, key,
                                                   ""))
                                            insert_alert_monitor(alert_dict)
                                        del pending_delete[key]
                                    break
                            # If none of those conditions match, at least note that the file still exists (if applicable).
                            if has_key(event_object, pending_delete):
                                pending_delete[event_object]['alive'] = True
                    # Event 4659 = a handle was requested with intent to delete
                    elif event_id == 4659:
                        alert_dict['action'] = DELETE_FILE_ACTION_MSG
                        alert_dict['note'] = ''
                        print(
                            "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s."
                            % (event_time, event_user, event_computer,
                               DELETE_FILE_ACTION_MSG, event_object, ""))
                        insert_alert_monitor(alert_dict)
                    # This delete confirmation doesn't happen when objects are moved/renamed;
                    # it does when files are created/deleted/recycled.
                    elif event_id == 4660:
                        for key in pending_delete.keys():
                            # print(event.StringInserts[5], pending_delete[key]['handle_id'])
                            if pending_delete[key]['handle_id'] == event.StringInserts[5] \
                                    and pending_delete[key]['user'] == event_user:
                                pending_delete[key]['confirmed'] = True
                        # msg = win32evtlogutil.SafeFormatMessage(event, log_type)
            total = total + len(events)
        win32evtlog.CloseEventLog(handle)
        msg = "Done read event_log. Scan: " + str(total) + "/" + str(
            num_records) + "."
        return SUCCESS_CODE, msg
    except Exception as e:
        print(e, 123)
        return ERROR_CODE, "Cannot read windows event_log."
Ejemplo n.º 30
0
 def clear_event_log(self):
     hlog = win32evtlog.OpenEventLog(None, self.providerName)
     win32evtlog.ClearEventLog(hlog, None)
     win32evtlog.CloseEventLog(hlog)