Saturday, November 12, 2022

A Simple Event Log Viewer in Python

Windows Event Logs are very useful in analyzing the history of an attack. Every attacks that has taken place leaves a footprint and this can be found on the Windows Event Logs. Even if the attacker knows how to erase her footprint, there will still be a log event that records the deletion. But one prevention of this deletion of event logs is to have a redundant storage of the logs.

In today's post, I created a simple python program that will read some of the event logs(I prepared only one event which the File Modification Event). Ideally, Cyber Forensic Analysts would primarily look at the following Event Logs(Source: Monitoring Windows Event Logs - A Tutorial):

User logon/logoff
computer logon/logoff/restart
Access to objects, files and folders
System time is modified
Audit logs are cleared

Each of these events have different Data Structures, I have not studied the rest and so far, I only looked at the File Modification Event.

The program I created will read all 4663 events( the File Modification Event) that recorded the previous one hour and print at the terminal. I will try to add more features of this program in my future post. In my previous post(2 Python Programs that are useful in Cyber Security),  I have created a program that will monitor any file changes on a specific folder. The limitation of this program is, it does not detect who made the changes. That is one of the reasons why reading the event logs is the only way to display who made the changes.

The following fields are shown:

Event Category
Time Generated
Source Name
Event ID
Event Type
Event Data: Username that Modified the file and the File Modified.

 Here's an example:

Event Category: 12800
Time Generated: 2022-11-13 14:33:59
Source Name: Microsoft-Windows-Security-Auditing
Event ID: 4663
Event Type: 8
Event Data:
John C:\frontdoor\haha.py

The complete list of Event ID which served as my reference can be found at this article: Appendix L: Events to Monitor.

I also added a filter to exclude other usernames that are not valid username(just for some demo only).  In the future, I plan to save the retrieved event logs to mysql database and  create a dashboard that will read log events in real time and display it using plotly. Some existing dashboards on the internet will serve as my guide such as this one(source) :



By default, The event id 4663 is disabled, so to enable it, this guide shows how: How to enable file and folder access auditing in Windows Server. Another useful article about understanding windows log events is Windows Logging Basics. It serve also as one of my reference for writing this post.

And finally, here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import win32evtlog # requires pywin32 pre-installed
import time
import datetime
import wmi

#import mysql.connector as mysql
w=wmi.WMI()
unames = []
for u in w.Win32_UserAccount(["Name"]):
    unames.append(u.Name)
print (unames )   
server = 'localhost' # name of the target computer to get event logs
logtype = 'Security' #'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)
begin_sec = time.time()
begin_time = time.strftime('%H:%M:%S  ', time.localtime(begin_sec))
number_of_hours_to_look_back = 1
seconds_per_hour = 60 * 60
how_many_seconds_back_to_search = seconds_per_hour * number_of_hours_to_look_back
def date2sec(evt_date):
    dt = datetime.datetime.strptime(evt_date, "%a %b %d %H:%M:%S %Y")
    return dt.timestamp()

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
          the_time = event.TimeGenerated.Format()
          seconds = date2sec(the_time)
          if seconds < begin_sec - how_many_seconds_back_to_search: break
          
          if event.EventID == 4663 and  event.StringInserts[1] in unames:
          #if event.EventCategory == 'File System':  
            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)
            #print(dir(event))
            data = event.StringInserts
          #print(dir(event.StringInserts))
            if data:
               
                print ('Event Data:')
                print(data[1] + ' ' + data[6])
                #for msg in data:
                #    print (msg)
            print(' ')
            #time.sleep(5)
    if seconds < begin_sec - how_many_seconds_back_to_search: break            



            

No comments:

Post a Comment