Example #1
0
    def run(self):

        self.hand = win32evtlog.OpenEventLog(self.server, self.logtype)
        global time_limit
        flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEEK_READ
        prevNumOfRecs = win32evtlog.GetNumberOfEventLogRecords(self.hand)
        evnthndl = CreateEvent(None, True, False, None)
        win32evtlog.NotifyChangeEventLog(self.hand, evnthndl)
        levels_dict = {1: 'ERROR', 2: 'WARNING', 4: 'INFO'}
        while True:
            print('hi')
            evntsgnld = WaitForSingleObject(evnthndl, 10000)
            if evntsgnld == WAIT_OBJECT_0:
                print('New event: \n')
                numOfRec = win32evtlog.GetNumberOfEventLogRecords(self.hand)
                NumOfNewRecs = numOfRec - prevNumOfRecs
                offset = numOfRec - NumOfNewRecs
                events = win32evtlog.ReadEventLog(self.hand, flags, offset + 1)
                for event in events:
                    # 4 Info, 1 Error, 2 Warning... 3 should be Debug?
                    evJson = {}
                    datetime = str(event.TimeGenerated)
                    evJson["logged_date"] = datetime.split(" ")[0]
                    evJson["logged_time"] = datetime
                    evJson["process"] = str(event.SourceName)
                    evJson["host"] = str(event.ComputerName)
                    if not event.EventType in levels_dict.keys():
                        evJson["severity"] = "Unknown"
                    else:
                        evJson["severity"] = str(levels_dict[event.EventType])
                    evJson["message"] = str(
                        win32evtlogutil.FormatMessage(event, self.logtype))
                    ev = evJson["logged_time"] + " " + evJson["process"] + " " + \
                     evJson["host"] + " " + evJson["severity"] + \
                     " " + evJson["message"]

                    filter_pattern = re.compile(event_logs["filter_by"])
                    if (event_logs["filter_by"] == ""
                            or filter_pattern.search(ev)):
                        logs.append(evJson)
                        if (len(logs) >= batch_size
                                or time.time() > time_limit):
                            now = time.time()
                            time_limit = now + max_time
                            sendLogs(logs)
                            logs.clear()
                        print(" EVENT: \n")
                        print(evJson)
                        # print("\n All events: \n")
                        # print(logs)
                        print("\n\n")
                ResetEvent(evnthndl)
                prevNumOfRecs = numOfRec
Example #2
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()
Example #3
0
def ParseEvents(eventtype, limit=None, server=None): 

    server = None
    hand = win32evtlog.OpenEventLog(server,eventtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    events = 1
    count = 0

    while events:
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                count += 1
                if count <= 500:
                    if interestingEvent(event,whitelist):
                        time = "date_time=\"" + str(event.TimeGenerated) + "\""
                        cat = "type=\"" + str(event.SourceName) + "\""
                        eventID = "eventid=\"" + str(event.EventID & 0x1FFFFFFF) + "\""
                        strings = "data=\"" + str(event.StringInserts).replace("\\\\","\\").replace("u'","'").replace("%%","") + "\""
                        result = []
                        result.append((time, cat, eventID, strings))
                        yield result
                
                else:
                    break
Example #4
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)
Example #5
0
    def getEventLogs(self, server, logtype, logPath):
        """
        Get the event logs from the specified machine according to the
        logtype (Example: Application) and save it to the appropriately
        named log file
        """
        print("Logging %s events" % logtype)
        log = codecs.open(logPath, encoding='utf-8', mode='w')
        line_break = '-' * 80

        log.write("\n%s Log of %s Events\n" % (server, logtype))
        log.write("Created: %s\n\n" % time.ctime())
        log.write("\n" + line_break + "\n")
        hand = win32evtlog.OpenEventLog(server, logtype)
        total = win32evtlog.GetNumberOfEventLogRecords(hand)
        print("Total events in %s = %s" % (logtype, total))
        flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        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'
        }

        try:
            events = 1
            while events:
                events = win32evtlog.ReadEventLog(hand, flags, 0)

                for ev_obj in events:
                    the_time = ev_obj.TimeGenerated.Format(
                    )  #'12/23/99 15:54:09'
                    evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID))
                    computer = str(ev_obj.ComputerName)
                    cat = ev_obj.EventCategory
                    record = ev_obj.RecordNumber
                    msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype)

                    source = str(ev_obj.SourceName)
                    if not ev_obj.EventType in evt_dict.keys():
                        evt_type = "unknown"
                    else:
                        evt_type = str(evt_dict[ev_obj.EventType])
                    log.write("Event Date/Time: %s\n" % the_time)
                    log.write("Event ID / Type: %s / %s\n" %
                              (evt_id, evt_type))
                    log.write("Currently Active User(s): %s\n" %
                              self.currentUsers)
                    log.write("Record #%s\n" % record)
                    log.write("Source: %s\n\n" % source)
                    log.write(msg)
                    log.write("\n\n")
                    log.write(line_break)
                    log.write("\n\n")
        except:
            print(traceback.print_exc(sys.exc_info()))

        print("Log creation finished. Location of log is %s" % logPath)
Example #6
0
    def _list_evt_xp(self, server, logtype):
        """Retrieves the contents of the event log for Windows XP"""
        self.logger.info('Exporting logs for : ' + logtype)
        hand = win32evtlog.OpenEventLog(server, logtype)
        flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        total = win32evtlog.GetNumberOfEventLogRecords(hand)
        sum_evt = 0
        while True:
            events = win32evtlog.ReadEventLog(hand, flags, 0)
            sum_evt += len(events)
            if events:
                for event in events:
                    data = event.StringInserts
                    date = datetime.datetime(event.TimeGenerated.year, event.TimeGenerated.month,
                                             event.TimeGenerated.day, event.TimeGenerated.hour,
                                             event.TimeGenerated.minute, event.TimeGenerated.second).strftime(
                        '%d/%m/%Y %H:%M:%S')

                    # print date + ' : ' + log_type + ' -> ' + log_data
                    if data:
                        yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode(
                            event.EventType), date, list(data)
                    else:
                        yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode(
                            event.EventType), date, []
            if sum_evt >= total:
                break
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)
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)
Example #9
0
    def RetrieveEvent(self):
        Datmsg = ''
        hand = win32evtlog.OpenEventLog('localhost',self.LogType)
        flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
        total = win32evtlog.GetNumberOfEventLogRecords(hand)
        ev = 0
        while ev != int(self.NumEvt):
            events = win32evtlog.ReadEventLog(hand, flags,0)
            if events:
                for event in events:
                    if (event.EventID == int(self.EvntID) or event.EventID == int(self.EvntIdII)) and (event.SourceName == self.EvtSourceName or event.SourceName == self.EvtSourceNameII):

                        self.Datapayload["EvtSourceName"] = event.SourceName
                        self.Datapayload["EvntID"]= self.EvntID
                        self.Datapayload['TimeGenerated']= str(event.TimeGenerated)
                        #print(self.Datapayload)
                        data = event.StringInserts
                        if data:

                            for msg in data:

                                Datmsg = Datmsg + msg
                                #print(msg)
                                self.Datapayload["EventData"]= Datmsg

                        ev += 1
            else:
                ev += 1
        self.Datapayload['UserName'] = self.UserName
        self.Datapayload['ComputerName'] = os.environ['COMPUTERNAME']
        return self.Datapayload
Example #10
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")
Example #11
0
def get_last_record(logtype):
    try:
        with eventlog(logtype) as log_handle:
            oldest = win32evtlog.GetOldestEventLogRecord(log_handle)
            total = win32evtlog.GetNumberOfEventLogRecords(log_handle)
            result = oldest + total - 1
            return result if result >= 0 else 0
    except Exception:
        return 0
def get_last_record(logtype):
    try:
        with eventlog(logtype) as log_handle:
            oldest = win32evtlog.GetOldestEventLogRecord(log_handle)  # pylint: disable=c-extension-no-member
            total = win32evtlog.GetNumberOfEventLogRecords(log_handle)  # pylint: disable=c-extension-no-member
            result = oldest + total - 1
            return result if result >= 0 else 0
    except Exception:
        return 0
Example #13
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)
Example #14
0
 def getLogs(self):
     for log in self.log_holder.keys():
         hand = win32evtlog.OpenEventLog(self.computer, log)
         numRecords = win32evtlog.GetNumberOfEventLogRecords(hand)
         flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
         while 1:
             events = win32evtlog.ReadEventLog(hand, flags, 0)
             if not events:
                 break
             for event in events:
                 self.log_holder[log].append(event)
Example #15
0
def monitEventlog(root, args, engine, baseline):
    server = "localhost"
    source_type = "Microsoft-Windows-Sysmon/Operational"
    num_events = 0

    h_log = win32evtlog.OpenEventLog(server, source_type)
    flags = win32evtlog.EVENTLOG_FORWARDS_READ|\
      win32evtlog.EVENTLOG_SEQUENTIAL_READ

    total_events = win32evtlog.GetNumberOfEventLogRecords(h_log)
    h_evt = win32event.CreateEvent(None, 1, 0, "evt0")
    win32evtlog.NotifyChangeEventLog(h_log, h_evt)

    while True:
        events_read = []

        while True:
            aux = win32evtlog.ReadEventLog(h_log, flags, 0)
            if not aux:
                break
            events_read += aux

        if events_read:

            num_events += len(events_read)
            log.debug("Read from eventlog: %d  - Total readed: %d \r" %\
              (len(events_read), num_events))

            for event in events_read:
                req_parsed = {}
                if event.EventID in EVENTLOG_EVENTID:
                    req_parsed = parseEventlogIDx(SYSMON_SCHEMA, event, server)
                    try:
                        actions_list = getListOfActions(req_parsed)
                    except:
                        log.error("Missing Sysmon/Operational registry key")
                        log.error("Add key located in RegistryKey directory")
                        log.error("See README for more info")
                        exit(1)

                    for action in actions_list:
                        pnode = addToProcessTree(action, root)
                        # Baseline engine actions
                        if pnode:
                            baseline.runActionCheck(pnode, action)
                            baseline.fireAlert(pnode)

            # Wait for proccess all the tree
            if (num_events >= total_events):
                engine.run(root)

                log.debug("Waiting for events on eventlog")
                wait_result = win32event.WaitForSingleObject(h_evt, -1)
Example #16
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)
def read_logs(api_url, regex):
    server = 'localhost'
    logtype = 'Security'
    filehandler = win32evtlog.OpenEventLog(server, logtype)
    eventhandler = win32event.CreateEvent(None, 1, 0, 'wait')
    flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    win32evtlog.NotifyChangeEventLog(filehandler, eventhandler)

    cursorlog = win32evtlog.GetNumberOfEventLogRecords(filehandler)
    new_logs = skip_old_logs(cursorlog, filehandler, flags)
    map(lambda e: handle_event(e, api_url, regex), new_logs)

    while True:
        result = win32event.WaitForSingleObject(eventhandler, 1)
        if not result:
            cursorlog = win32evtlog.GetNumberOfEventLogRecords(filehandler)
            while True:
                readlog = win32evtlog.ReadEventLog(filehandler, flags,
                                                   cursorlog)
                if len(readlog) == 0:
                    break
                for event in readlog:
                    handle_event(event, api_url, regex)
Example #18
0
def todays_events(server,logtype,ids=[4648]):
    import datetime
    from vyperlogix import misc
    from vyperlogix.misc import _utils
    from vyperlogix.hash.lists import HashedLists
    from vyperlogix.classes.SmartObject import SmartObject
    
    import win32evtlog
    
    #logon_event_ids = [id for id in [int(e.id) for e in events_by_tokens.get('logon',[])] if (id > 999)]
    logon_event_ids = ids if (misc.isList(ids)) else [4648]
    
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    
    now = _utils.today_localtime()
    
    seconds_in_day = 24*60*60
    
    __todays_events__ = []
    
    __running__ = True
    while (__running__):
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                if (event.EventID in logon_event_ids):
                    #print 'Event Category:', event.EventCategory
                    #print 'Time Generated:', event.TimeGenerated
                    dt = _utils.getFromDateTimeStr(event.TimeGenerated.Format(),format='%m/%d/%y %H:%M:%S')
                    delta = max(now,dt) - min(now,dt)
                    #print 'delta.total_seconds()=%s' % (delta.total_seconds())
                    if (delta.total_seconds() < seconds_in_day):
                        __todays_events__.append(event)
                    else:
                        __running__ = False
                        break
                    #print 'Source Name:', event.SourceName
                    #print 'Event ID:', event.EventID
                    #print 'Event Type:', event.EventType
                    #data = event.StringInserts
                    #if data:
                        #print 'Event Data:'
                        #for msg in data:
                            #print msg
                    #print '='*40
        else:
            break
    return __todays_events__
    def GetEvents(self, evtmgr, log_type,stub):
        self.clearEvt(log_type)
        hand = win32evtlog.OpenEventLog("localhost", log_type)  # Handle the connection to EventViewer
        flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        last_check = win32evtlog.GetNumberOfEventLogRecords(hand)
        self.send_report(stub,"Information Message", "Thread "+log_type + " start to run")

        evtmgr.hostname = self._station_name_  # Using Socket we can know the PC name
        evtmgr.username = getpass.getuser()     # Using getpass we can know what user is current using
        evtmgr.os = platform.system()           # Using platform to get OS brand
        evtmgr.ip_add = socket.gethostbyname(evtmgr.hostname) # Get the IP Address from socket
        evtmgr.mac_add = get_mac_address(ip=(socket.gethostbyname(evtmgr.hostname))) # Get the MAC_Address

        # ! Important: This while must stop when service is stopped ! #
        while self.keepAlive():
            curr_check = win32evtlog.GetNumberOfEventLogRecords(hand)
            if curr_check > last_check:
                events = win32evtlog.ReadEventLog(hand, flags, curr_check)
                for event in events:
                    evtmgr.id = str(event.EventID)
                    evtmgr.time.FromDatetime(event.TimeGenerated)
                    evtmgr.type = str(event.EventType)
                    evtmgr.src = event.SourceName
                    evtmgr.cat = str(event.EventCategory)
                    data = event.StringInserts
                    data_list = evtmgr.dataList

                    if data:
                        for msg in data:
                            data_list.append(msg)
                    # Push log return true if completed
                    if(stub.PushLog(evtmgr)):   # Debug in gRPC to return value
                        last_check = curr_check
                    else:
                        self.send_report(stub, "Error Message",
                                         "Thread " + log_type + " fail to push from device")
Example #20
0
    def __init__(self, regex_filter=None, interval=None, kind='Security'):
        if os.name != 'nt':
            raise OSException('This parser works only on Windows machine!')

        self.regex_filter = regex_filter
        self.interval = interval
        # ova dva bih mogao citati iz configa isto
        # ili mozda ipak ni ne treba
        self.server = 'localhost'  # name of the target computer to get event logs
        self.logtype = kind
        self.hand = win32evtlog.OpenEventLog(self.server, self.logtype)
        self.flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        self.total = win32evtlog.GetNumberOfEventLogRecords(self.hand)
        Thread.__init__(self)
        self.last_log_timestamp = datetime.now()
Example #21
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)
Example #22
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
def display_logs(logtype):
    global display, prin
    hand = win32evtlog.OpenEventLog(server, logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    x = 0

    if prin == 1:
        filename = folder_loc + "\\" + logtype + "_Logs" + ".txt"
        file = open(filename, 'w')

    while x <= int(num_of_logs):
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        if events:
            for event in events:
                x += 1
                if display == 1:
                    print("Record Number:", event.RecordNumber)
                    print('Event Category:', event.EventCategory)
                    print("Source Name:", event.SourceName)
                    print('Time Generated:', event.TimeGenerated)
                    print('Event ID:', event.EventID)
                    print('Event Type:', event.EventType)
                    data = event.StringInserts
                    if data:
                        print('Event Data:')
                        print(str(data))
                        #for msg in data:
                        #    print(msg)
                    print("\n\n")

                if prin == 1:
                    file.write("Record Number:" + str(event.RecordNumber))
                    file.write('\nEvent Category:' + str(event.EventCategory))
                    file.write("\nSource Name:" + event.SourceName)
                    file.write('\nTime Generated:' + str(event.TimeGenerated))
                    file.write('\nEvent ID:' + str(event.EventID))
                    file.write('\nEvent Type:' + str(event.EventType))
                    data = event.StringInserts
                    if data:
                        file.write('\nEvent Data:')
                        file.write(str(data))
                        #for msg in data:
                        #    file.write("\n" + msg)
                    file.write("\n\n")
Example #24
0
def get_number_of_events(log_name, target_computer=None):
    '''
    Gets the number of events in a log.

    log_name
        str

    target_computer
        None or str

    return
        int
    '''

    handler = _get_event_handler(log_name, target_computer)
    number_of_events = win32evtlog.GetNumberOfEventLogRecords(handler)
    _close_event_handler(handler)
    return number_of_events
    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)
Example #26
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')
Example #27
0
def readevents(path):
    logHandle = win32evtlog.OpenBackupEventLog(
        None, path)  # None=NULL means local host
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(logHandle)
    LOGGER.info("Total number of records for {} is: {}".format(path, total))

    # if "security" in path.lower():
    #     logType = "Security"
    # elif "application" in path.lower():
    #     logType = "Application"
    # elif "system" in path.lower():
    #     logType = "System"
    # else:
    #     LOGGER.error("Unknown log type - put something in path")
    #     sys.exit(-1)
    event_dict = None

    while True:
        events = win32evtlog.ReadEventLog(logHandle, flags, 0)
        if events:
            for event in events:
                event_dict = {}
                event_dict['TimeGenerated'] = time.strftime(
                    "%#c", time.localtime(int(event.TimeGenerated)))
                event_dict['SourceName'] = event.SourceName
                event_dict['Id'] = event.EventID
                event_dict['EventType'] = event.EventType
                event_dict['ComputerName'] = event.ComputerName

                if event.StringInserts:
                    event_dict['data'] = "|".join(event.StringInserts)

                description = expandString(event)
                event_dict['Description'] = description
                if description:
                    event_dict.update(description_to_fields(description))
                    first_line = description.split("\r\n")[0]
                    event_dict['Short Description'] = first_line
                yield event_dict
        else:
            break
Example #28
0
def isEvent():
	elog = win32evtlog.OpenEventLog(None, "Application")
	nr = win32evtlog.GetNumberOfEventLogRecords(elog)
	if nr>0:
		events = win32evtlog.ReadEventLog(elog, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ,0)
		if events:
			for event in events:
				if int(event.EventID) == 1000 and int(event.EventCategory) == 100:
					#Of course it's not enough but at least something
					data = event.StringInserts
					crash = CrashReport()
					crash.location = data[0] + "!" +data[3]
					crash.faultAddr = "UNKNOWN"
					crash.code = "UNKNOWN"
					crash.nearNull = True
					crash.type = data[6]
					crash.stack = "UNKNOWN"
					crash.info = "UNKNOWN"
					return crash
	return None
Example #29
0
def get_ps():
    server = 'localhost' # name of the target computer to get event logs
    logtype = 'Windows PowerShell' # 'Application' # 'Security' # 'Windows PowerShell'
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    while True:
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                data = event.StringInserts
                if data:
                    for msg in data:
                        msg = msg.split("\n")
                        for i in msg :
                            if "HostApplication" in i:
                                path = i.split()[-1][1:len(i.split()[-1])-1]
                                if os.path.isabs(path):
                                    inser_to_paths(path)
        else:
            break
Example #30
0
def read_log():
    server = 'localhost'  # name of the target computer to get event logs
    logtype = 'System'  # 'Application' # 'Security'
    hand = win32evtlog.OpenEventLog(server, logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)

    while True:
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        if events:
            for event in events:
                print('Event Category:', event.EventCategory)
                print('Time Generated:', event.TimeGenerated)
                print('Source Name:', event.SourceName)
                print('Event ID:', event.EventID)
                print('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print('Event Data:')
                    for msg in data:
                        print(msg)
                print()