Compare commits

..

No commits in common. '7b538e9855b9e6d2174c962820cced582ed06275' and '3528a52e8b764ec758629e85141a66b906796d66' have entirely different histories.

@ -1,864 +0,0 @@
import traceback
import logging
from lib.Banner import *
import argparse
import pandas as pd
import lib.EvtxDetection as EvtxDetection
import lib.O365Hunter as O365Hunter
import lib.CSVDetection as CSVDetection
import lib.EvtxHunt as EvtxHunt
import lib.SigmaHunter as SigmaHunter
from evtx import PyEvtxParser
from sys import exit
from pytz import timezone
from dateutil import tz
import glob
import os
import re
from pathlib import Path as libPath
from datetime import datetime
import dateutil.parser
import multiprocessing
import time
import pickle
import platform
timestart=None
timeend=None
Output=""
Path=""
Security_path=""
system_path=""
scheduledtask_path=""
defender_path=""
powershell_path=""
powershellop_path=""
terminal_path=""
temp_dir="temp"
winrm_path=""
sysmon_path=""
objectaccess=False
processexec=False
logons=False
frequencyanalysis=False
allreport=False
Security_path_list=[]
system_path_list=[]
scheduledtask_path_list=[]
defender_path_list=[]
powershell_path_list=[]
powershellop_path_list=[]
terminal_path_list=[]
terminal_Client_path_list=[]
winrm_path_list=[]
sysmon_path_list=[]
group_policy_path_list=[]
SMB_SERVER_path_list=[]
SMB_CLIENT_path_list=[]
UserProfile_path_list=[]
RDPClient_Resolved_User=[]
WinRM_Resolved_User=[]
input_timezone=tz.tzlocal()
CPU_Core=0
Logon_Events=[{'Date and Time':[],'timestamp':[],'Event ID':[],'Account Name':[],'Account Domain':[],'Logon Type':[],'Logon Process':[],'Source IP':[],'Workstation Name':[],'Computer Name':[],'Channel':[],'Original Event Log':[]}]
Executed_Powershell_Summary=[{'Command': [], 'Number of Execution': []}]
Executed_Process_Summary=[{'Process Name':[],'Number of Execution':[]}]
TerminalServices_Summary=[{'User':[],'Number of Logins':[]}]
Security_Authentication_Summary=[{'User':[],'Number of Failed Logins':[],'Number of Successful Logins':[]}]
Sysmon_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
WinRM_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'UserID':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Security_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
System_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Service Name':[],'Image Path':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
ScheduledTask_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Schedule Task Name':[],'Image Path':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Powershell_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Powershell_Operational_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
TerminalServices_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'User':[],'Source IP':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
TerminalServices_RDPClient_events=[{'Date and Time': [], 'timestamp': [], 'Detection Rule': [], 'Severity': [], 'Detection Domain': [],'Event Description': [], 'Event ID': [], 'UserID': [], 'Source IP': [], 'Computer Name': [], 'Channel': [],'Original Event Log': []}]
Windows_Defender_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Timesketch_events=[{'message':[],'timestamp':[],'datetime':[],'timestamp_desc':[],'Event Description':[],'Severity':[],'Detection Domain':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Object_Access_Events=[{'Date and Time':[],'timestamp':[],'Event ID':[],'Account Name':[],'Account Domain':[],'Object Name':[],'Object Type':[],'Process Name':[],'Computer Name':[],'Channel':[],'Original Event Log':[]}]
Group_Policy_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Group Policy Name':[],'Policy Extension Name':[],'Event ID':[],'Original Event Log':[],'Computer Name':[],'Channel':[]}]
Executed_Process_Events=[{'DateTime':[],'timestamp':[],'EventID':[],'ProcessName':[],'User':[],'ParentProcessName':[],'RawLog':[]}]
SMB_Server_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Client Address':[],'UserName':[],'Share Name':[],'File Name':[],'Event ID':[],'Computer Name':[],'Channel':[],'Original Event Log':[]}]
SMB_Client_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Share Name':[],'File Name':[],'Event ID':[],'Computer Name':[],'Channel':[],'Original Event Log':[]}]
User_SIDs = {'User': [], 'SID': []}
Frequency_Analysis_Security={}
Frequency_Analysis_Security={}
Frequency_Analysis_Windows_Defender={}
Frequency_Analysis_SMB_Client={}
Frequency_Analysis_Group_Policy={}
Frequency_Analysis_Powershell_Operational={}
Frequency_Analysis_Powershell={}
Frequency_Analysis_ScheduledTask={}
Frequency_Analysis_WinRM={}
Frequency_Analysis_System={}
Frequency_Analysis_Sysmon={}
Frequency_Analysis_SMB_Server={}
Frequency_Analysis_TerminalServices={}
def evtxdetect_auto():
global timestart,timeend,logons,Output,allreport,SMB_Server_events,User_SIDs,SMB_Client_events,TerminalServices_RDPClient_events,Frequency_Analysis_TerminalServices,Executed_Process_Events,Group_Policy_events,Object_Access_Events,input_timezone,Logon_Events,Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,Timesketch_events,TerminalServices_Summary,Security_Authentication_Summary,Executed_Powershell_Summary
process_list = []
try:
#print(Security_path)
userprofile=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (UserProfile_path_list,EvtxDetection.detect_events_UserProfileService_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core))
userprofile.start()
process_list.append(userprofile)
except IOError :
print("Error Analyzing User Profile logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing User Profile logs")
logging.error(traceback.format_exc())
try:
#print(Security_path)
sec=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (Security_path_list,EvtxDetection.detect_events_security_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
sec.start()
process_list.append(sec)
except IOError :
print("Error Analyzing Security logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Security logs")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(system_path_list,EvtxDetection.detect_events_system_log,input_timezone,timestart,timeend)
sys=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (system_path_list,EvtxDetection.detect_events_system_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
sys.start()
process_list.append(sys)
except IOError :
print("Error Analyzing System logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing System logs ")
logging.error(traceback.format_exc())
try :
#EvtxDetection.multiprocess(powershellop_path_list,EvtxDetection.detect_events_powershell_operational_log,input_timezone,timestart,timeend)
pwshop=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (powershellop_path_list,EvtxDetection.detect_events_powershell_operational_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
pwshop.start()
process_list.append(pwshop)
except IOError :
print("Error Analyzing Powershell Operational logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell Operational logs ")
logging.error(traceback.format_exc())
try :
#EvtxDetection.multiprocess(powershell_path_list,EvtxDetection.detect_events_powershell_log,input_timezone,timestart,timeend)
pwsh=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (powershell_path_list,EvtxDetection.detect_events_powershell_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
pwsh.start()
process_list.append(pwsh)
except IOError :
print("Error Analyzing Powershell logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell logs ")
logging.error(traceback.format_exc())
try :
#EvtxDetection.multiprocess(terminal_path_list,EvtxDetection.detect_events_TerminalServices_LocalSessionManager_log,input_timezone,timestart,timeend)
terminal=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (terminal_path_list,EvtxDetection.detect_events_TerminalServices_LocalSessionManager_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
terminal.start()
process_list.append(terminal)
except IOError :
print("Error Analyzing TerminalServices LocalSessionManager logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing TerminalServices LocalSessionManager logs")
logging.error(traceback.format_exc())
try :
#EvtxDetection.multiprocess(terminal_path_list,EvtxDetection.detect_events_TerminalServices_LocalSessionManager_log,input_timezone,timestart,timeend)
terminal_client=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (terminal_Client_path_list,EvtxDetection.detect_events_TerminalServices_RDPClient_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
terminal_client.start()
process_list.append(terminal_client)
except IOError :
print("Error Analyzing TerminalServices RDP Client logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing TerminalServices RDP Client logs")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(scheduledtask_path_list,EvtxDetection.detect_events_scheduled_task_log,input_timezone,timestart,timeend)
scheduled=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (scheduledtask_path_list,EvtxDetection.detect_events_scheduled_task_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
scheduled.start()
process_list.append(scheduled)
except IOError :
print("Error Analyzing Scheduled Task logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Scheduled Task logs ")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(defender_path_list,EvtxDetection.detect_events_windows_defender_log,input_timezone,timestart,timeend)
defen=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (defender_path_list,EvtxDetection.detect_events_windows_defender_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
defen.start()
process_list.append(defen)
except IOError :
print("Error Analyzing Windows Defender logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Windows Defender logs ")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(winrm_path_list,EvtxDetection.detect_events_Microsoft_Windows_WinRM,input_timezone,timestart,timeend)
winrm=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (winrm_path_list,EvtxDetection.detect_events_Microsoft_Windows_WinRM,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
winrm.start()
process_list.append(winrm)
except IOError :
print("Error Analyzing WinRM logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing WinRM logs ")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(sysmon_path_list,EvtxDetection.detect_events_Sysmon_log,input_timezone,timestart,timeend)
sysmon=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (sysmon_path_list,EvtxDetection.detect_events_Sysmon_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
sysmon.start()
process_list.append(sysmon)
except IOError :
print("Error Analyzing Sysmon logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Sysmon logs ")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(group_policy_path_list,EvtxDetection.detect_events_group_policy_log,input_timezone,timestart,timeend)
gp=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (group_policy_path_list,EvtxDetection.detect_events_group_policy_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
gp.start()
process_list.append(gp)
except IOError :
print("Error Analyzing Group Policy logs ")
print("File Path Does Not Exist")
#except Exception as e:
# print("Error Analyzing Group Policy logs ")
# logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(SMB_SERVER_path_list,EvtxDetection.detect_events_SMB_Server_log,input_timezone,timestart,timeend)
smbserv=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (SMB_SERVER_path_list,EvtxDetection.detect_events_SMB_Server_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
smbserv.start()
process_list.append(smbserv)
except IOError :
print("Error Analyzing SMB Server logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Group Policy logs ")
logging.error(traceback.format_exc())
try:
#EvtxDetection.multiprocess(SMB_CLIENT_path_list,EvtxDetection.detect_events_SMB_Client_log,input_timezone,timestart,timeend)
smbcli=multiprocessing.Process(target= EvtxDetection.multiprocess, args = (SMB_CLIENT_path_list,EvtxDetection.detect_events_SMB_Client_log,input_timezone,timestart,timeend,objectaccess,processexec,logons,frequencyanalysis,allreport,Output,CPU_Core,temp_dir))
smbcli.start()
process_list.append(smbcli)
except IOError :
print("Error Analyzing SMB Client logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Group Policy logs ")
logging.error(traceback.format_exc())
for process in process_list:
process.join()
print("preparing results")
Sysmon_events = EvtxDetection.Sysmon_events
WinRM_events =EvtxDetection.WinRM_events
Security_events =EvtxDetection.Security_events
System_events =EvtxDetection.System_events
ScheduledTask_events =EvtxDetection.ScheduledTask_events
Powershell_events =EvtxDetection.Powershell_events
Powershell_Operational_events =EvtxDetection.Powershell_Operational_events
TerminalServices_events =EvtxDetection.TerminalServices_events
TerminalServices_RDPClient_events =EvtxDetection.TerminalServices_RDPClient_events
Windows_Defender_events =EvtxDetection.Windows_Defender_events
Timesketch_events =EvtxDetection.Timesketch_events
TerminalServices_Summary=EvtxDetection.TerminalServices_Summary
Executed_Process_Summary=EvtxDetection.Executed_Process_Summary
Executed_Powershell_Summary=EvtxDetection.Executed_Powershell_Summary
Security_Authentication_Summary =EvtxDetection.Security_Authentication_Summary
Logon_Events =EvtxDetection.Logon_Events
Object_Access_Events=EvtxDetection.Object_Access_Events
Group_Policy_events=EvtxDetection.Group_Policy_events
Executed_Process_Events=EvtxDetection.Executed_Process_Events
SMB_Server_events=EvtxDetection.SMB_Server_events
SMB_Client_events=EvtxDetection.SMB_Client_events
Frequency_Analysis_Security=EvtxDetection.Frequency_Analysis_Security
Frequency_Analysis_Windows_Defender=EvtxDetection.Frequency_Analysis_Windows_Defender
Frequency_Analysis_SMB_Client=EvtxDetection.Frequency_Analysis_SMB_Client
Frequency_Analysis_Group_Policy=EvtxDetection.Frequency_Analysis_Group_Policy
Frequency_Analysis_Powershell_Operational=EvtxDetection.Frequency_Analysis_Powershell_Operational
Frequency_Analysis_Powershell=EvtxDetection.Frequency_Analysis_Powershell
Frequency_Analysis_ScheduledTask=EvtxDetection.Frequency_Analysis_ScheduledTask
Frequency_Analysis_WinRM=EvtxDetection.Frequency_Analysis_WinRM
Frequency_Analysis_System=EvtxDetection.Frequency_Analysis_System
Frequency_Analysis_Sysmon=EvtxDetection.Frequency_Analysis_Sysmon
Frequency_Analysis_SMB_Server=EvtxDetection.Frequency_Analysis_SMB_Server
Frequency_Analysis_TerminalServices=EvtxDetection.Frequency_Analysis_TerminalServices
if os.path.exists(temp_dir + "_User_SIDs_report.csv"):
#User_SIDs = pd.DataFrame(pd.read_csv(temp_dir + "_User_SIDs_report.csv"))
User_SIDs = pd.DataFrame(pd.read_csv(temp_dir + "_User_SIDs_report.csv")).to_dict(orient='list')
else:
print(f"{temp_dir + '_User_SIDs_report.csv'} does not exist.")
#User_SIDs = pd.DataFrame(User_SIDs)
#User_SIDs=EvtxDetection.User_SIDs
resolveSID()
def auto_detect(path):
global input_timezone
EventID_rex = re.compile('<EventID.*>(.*)<\/EventID>', re.IGNORECASE)
Channel_rex = re.compile('<Channel.*>(.*)<\/Channel>', re.IGNORECASE)
Computer_rex = re.compile('<Computer.*>(.*)<\/Computer>', re.IGNORECASE)
if os.path.isdir(path):
files=list(libPath(path).rglob("*.[eE][vV][tT][xX]"))
#files=glob.glob(path+"/**/"+"*.evtx")
elif os.path.isfile(path):
files=glob.glob(path)
else:
print("Issue with the path" )
return
#print("hunting ( %s ) in files ( %s )"%(str_regex,files))
#user_string = input('please enter a string to convert to regex: ')
for file in files:
file=str(file)
print("Analyzing "+file)
try:
parser = PyEvtxParser(file)
except:
print("Issue analyzing "+file +"\nplease check if its not corrupted")
continue
try:
for record in parser.records():
Channel = Channel_rex.findall(record['data'])
if Channel[0].strip()=="Security":
Security_path_list.append(file)
break
if Channel[0].strip()=="System":
system_path_list.append(file)
break
if Channel[0].strip()=="Windows PowerShell":
powershell_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-PowerShell/Operational":
powershellop_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-TerminalServices-LocalSessionManager/Operational":
terminal_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-TaskScheduler/Operational":
scheduledtask_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-Windows Defender/Operational":
defender_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-WinRM/Operational":
winrm_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-Sysmon/Operational":
sysmon_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-GroupPolicy/Operational":
group_policy_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-SMBServer/Operational":
SMB_SERVER_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-SmbClient/Security":
SMB_CLIENT_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-User Profile Service/Operational":
UserProfile_path_list.append(file)
#print("file added")
break
if Channel[0].strip()=="Microsoft-Windows-TerminalServices-RDPClient/Operational":
terminal_Client_path_list.append(file)
#print("file added")
break
break
except:
print("issue assigning path")
evtxdetect_auto()
def threat_hunt(path,str_regex,eid,hunt_file):
global timestart,timeend,input_timezone, Output
import os
regex_file=[]
#try:
if 1==1:
if hunt_file is not None:
if os.path.isfile(hunt_file):
print(regex_file)
regex_file=open(hunt_file).read().split("\n")
regex_file.remove('')
print(regex_file)
else:
print("Issue with the hunt file path" )
return
if os.path.isdir(path):
files=list(libPath(path).rglob("*.[eE][vV][tT][xX]"))
elif os.path.isfile(path):
files=glob.glob(path)
else:
print("Issue with the path" )
return
#user_string = input('please enter a string to convert to regex: ')
if str_regex is not None:
regex=[str_regex]
elif str_regex is None and len(regex_file)>0:
regex=regex_file
print("hunting ( %s ) in files ( %s )"%(regex,files))
EvtxHunt.Evtx_hunt(files,regex,eid,input_timezone,Output,timestart,timeend)
#except Exception as e:
# print("Error in hunting module ")
def report():
global Output,User_SIDs
timesketch=Output+"_TimeSketch.csv"
Report=Output+"_Report.xlsx"
LogonEvents=Output+"_Logon_Events.csv"
ObjectAccess=Output+"_Object_Access_Events.csv"
ProcessEvents=Output+"_Process_Execution_Events.csv"
Collected_SIDs=Output+"_Collected_SIDs.csv"
print("preparing report")
if os.path.exists(temp_dir + "_User_SIDs_report.csv"):
User_SIDs = pd.DataFrame(pd.read_csv(temp_dir + "_User_SIDs_report.csv"))
else:
print(f"{temp_dir + '_User_SIDs_report.csv'} does not exist.")
User_SIDs = pd.DataFrame(User_SIDs)
if os.path.exists(temp_dir + "_Sysmon_report.csv"):
Sysmon = pd.DataFrame(pd.read_csv(temp_dir + "_Sysmon_report.csv"))
else:
print(f"{temp_dir + '_Sysmon_report.csv'} does not exist.")
Sysmon = pd.DataFrame(Sysmon_events[0])
if os.path.exists(temp_dir + "_System_report.csv"):
System = pd.DataFrame(pd.read_csv(temp_dir + "_System_report.csv"))
else:
print(f"{temp_dir + '_System_report.csv'} does not exist.")
System = pd.DataFrame(System_events[0])
if os.path.exists(temp_dir + "_Powershell_report.csv"):
Powershell = pd.DataFrame(pd.read_csv(temp_dir + "_Powershell_report.csv"))
else:
print(f"{temp_dir + '_Powershell_report.csv'} does not exist.")
Powershell = pd.DataFrame(Powershell_events[0])
if os.path.exists(temp_dir + "_Powershell_Operational_report.csv"):
Powershell_Operational = pd.DataFrame(pd.read_csv(temp_dir + "_Powershell_Operational_report.csv"))
else:
print(f"{temp_dir + '_Powershell_Operational_report.csv'} does not exist.")
Powershell_Operational = pd.DataFrame(Powershell_Operational_events[0])
if os.path.exists(temp_dir + "_Security_report.csv"):
Security = pd.DataFrame(pd.read_csv(temp_dir + "_Security_report.csv"))
else:
print(f"{temp_dir + '_Security_report.csv'} does not exist.")
Security = pd.DataFrame(Security_events[0])
if os.path.exists(temp_dir + "_TerminalServices_report.csv"):
TerminalServices = pd.DataFrame(pd.read_csv(temp_dir + "_TerminalServices_report.csv"))
else:
print(f"{temp_dir + '_TerminalServices_report.csv'} does not exist.")
TerminalServices = pd.DataFrame(TerminalServices_events[0])
if os.path.exists(temp_dir + "_WinRM_events_report.csv"):
WinRM = pd.DataFrame(pd.read_csv(temp_dir + "_WinRM_events_report.csv"))
#print(WinRM_Resolved_User)
if len(WinRM_Resolved_User)>0:
try:
WinRM['Resolved User Name']=WinRM_Resolved_User
WinRM=WinRM[['Date and Time','timestamp','Detection Rule','Severity','Detection Domain','Event Description','UserID','Resolved User Name','Event ID','Original Event Log','Computer Name','Channel']]
except:
print("Error resolving SIDs for WinRM")
else:
print(f"{temp_dir + '_WinRM_events_report.csv'} does not exist.")
WinRM = pd.DataFrame(WinRM_events[0])
if os.path.exists(temp_dir + "_TerminalServices_RDPClient_report.csv"):
TerminalClient = pd.DataFrame(pd.read_csv(temp_dir + "_TerminalServices_RDPClient_report.csv"))
#print(RDPClient_Resolved_User)
if len(RDPClient_Resolved_User) > 0:
try:
TerminalClient['Resolved User Name'] = RDPClient_Resolved_User
TerminalClient = TerminalClient[['Date and Time', 'timestamp', 'Detection Rule', 'Severity', 'Detection Domain', 'Event Description','Event ID', 'UserID', 'Resolved User Name', 'Source IP', 'Computer Name', 'Channel', 'Original Event Log']]
except:
print("Error resolving SIDs for Terminal Client")
else:
print(f"{temp_dir + '_TerminalServices_RDPClient_report.csv'} does not exist.")
TerminalClient = pd.DataFrame(TerminalServices_RDPClient_events[0])
if os.path.exists(temp_dir + "_Defender_report.csv"):
Windows_Defender = pd.DataFrame(pd.read_csv(temp_dir + "_Defender_report.csv"))
else:
print(f"{temp_dir + '_Defender_report.csv'} does not exist.")
Windows_Defender = pd.DataFrame(Windows_Defender_events[0])
if os.path.exists(temp_dir + "_ScheduledTask_report.csv"):
ScheduledTask = pd.DataFrame(pd.read_csv(temp_dir + "_ScheduledTask_report.csv"))
else:
print(f"{temp_dir + '_ScheduledTask_report.csv'} does not exist.")
ScheduledTask = pd.DataFrame(ScheduledTask_events[0])
if os.path.exists(temp_dir + "_Group_Policy_report.csv"):
GroupPolicy = pd.DataFrame(pd.read_csv(temp_dir + "_Group_Policy_report.csv"))
else:
print(f"{temp_dir + '_Group_Policy_report.csv'} does not exist.")
GroupPolicy = pd.DataFrame(Group_Policy_events[0])
if os.path.exists(temp_dir + "_SMB_Server_report.csv"):
SMBServer = pd.DataFrame(pd.read_csv(temp_dir + "_SMB_Server_report.csv"))
else:
print(f"{temp_dir + '_SMB_Server_report.csv'} does not exist.")
SMBServer = pd.DataFrame(SMB_Server_events[0])
if os.path.exists(temp_dir + "_SMB_Client_report.csv"):
SMBClient = pd.DataFrame(pd.read_csv(temp_dir + "_SMB_Client_report.csv"))
else:
print(f"{temp_dir + '_SMB_Client_report.csv'} does not exist.")
SMBClient= pd.DataFrame(SMB_Client_events[0])
# if os.path.exists(temp_dir + "_Executed_Powershell_report.csv"):
# ExecutedPowershell_Summary = pd.DataFrame(pd.read_csv(temp_dir + "_Executed_Powershell_report.csv"))
if os.path.exists(temp_dir + "Powershell_Execution_Events.pickle"):
with open(temp_dir + "Powershell_Execution_Events.pickle", 'rb') as handle:
#Authentication_Summary=pd.DataFrame(pickle.load(handle))
Powershell_Execution_dataframes=pickle.load(handle)
#print(Security_Authentication_dataframes[0])
result=pd.concat(Powershell_Execution_dataframes, axis=0)
#ExecutedProcess_Summary=result.groupby('User').agg({'Number of Failed Logins': 'sum', 'Number of Successful Logins': 'sum'})
ExecutedPowershell_Summary =result.groupby('Command',as_index=False)['Number of Execution'].sum()
else:
print(f"{temp_dir + '_Executed_Powershell_report.csv'} does not exist.")
ExecutedPowershell_Summary = pd.DataFrame(Executed_Powershell_Summary[0])
if os.path.exists(temp_dir + "Security_Authentication.pickle"):
with open(temp_dir + "Security_Authentication.pickle", 'rb') as handle:
#Authentication_Summary=pd.DataFrame(pickle.load(handle))
Security_Authentication_dataframes=pickle.load(handle)
#print(Security_Authentication_dataframes[0])
result=pd.concat(Security_Authentication_dataframes, axis=0)
Authentication_Summary=result.groupby('User',as_index=False).agg(
{'Number of Failed Logins': 'sum', 'Number of Successful Logins': 'sum'})
#print(Authentication_Summary)
#if os.path.exists(temp_dir + "_Security_Authentication_report.csv"):
#Authentication_Summary = pd.DataFrame(pd.read_csv(temp_dir + "_Security_Authentication_report.csv"))
else:
print(f"{temp_dir + '_Security_Authentication_report.csv'} does not exist.")
Authentication_Summary = pd.DataFrame(Security_Authentication_Summary[0])
# if os.path.exists(temp_dir + "_Executed_Process_report.csv"):
# ExecutedProcess_Summary = pd.DataFrame(pd.read_csv(temp_dir + "_Executed_Process_report.csv"))
if os.path.exists(temp_dir + "Executed_Process_Events.pickle"):
with open(temp_dir + "Executed_Process_Events.pickle", 'rb') as handle:
#Authentication_Summary=pd.DataFrame(pickle.load(handle))
Process_Execution_dataframes=pickle.load(handle)
#print(Security_Authentication_dataframes[0])
result=pd.concat(Process_Execution_dataframes, axis=0)
#ExecutedProcess_Summary=result.groupby('User').agg({'Number of Failed Logins': 'sum', 'Number of Successful Logins': 'sum'})
ExecutedProcess_Summary =result.groupby('Process Name',as_index=False)['Number of Execution'].sum()
#print(Authentication_Summary)
else:
print(f"{temp_dir + '_Executed_Process_report.csv'} does not exist.")
ExecutedProcess_Summary = pd.DataFrame(Executed_Process_Summary[0])
# TerminalClient = pd.DataFrame(pd.read_csv(temp_dir+"_TerminalServices_RDPClient_report.csv"))
# TerminalClient['Resolved User Name']=RDPClient_Resolved_User
# TerminalClient=TerminalClient[['Date and Time', 'timestamp', 'Detection Rule', 'Severity', 'Detection Domain','Event Description', 'Event ID', 'UserID','Resolved User Name', 'Source IP', 'Computer Name', 'Channel','Original Event Log']]
# Windows_Defender = pd.DataFrame(pd.read_csv(temp_dir+"_Defender_report.csv"))
# ScheduledTask = pd.DataFrame(pd.read_csv(temp_dir+"_ScheduledTask_report.csv"))
# GroupPolicy = pd.DataFrame(pd.read_csv(temp_dir+"_Group_Policy_report.csv"))
# SMBServer= pd.DataFrame(pd.read_csv(temp_dir+"_SMB_Server_report.csv"))
# SMBClient= pd.DataFrame(pd.read_csv(temp_dir+"_SMB_Clientr_report.csv"))
# WinRM['Resolved User Name']=WinRM_Resolved_User
# WinRM=WinRM[['Date and Time','timestamp','Detection Rule','Severity','Detection Domain','Event Description','UserID','Resolved User Name','Event ID','Original Event Log','Computer Name','Channel']]
Terminal_Services_Summary = TerminalServices['User'].value_counts().reset_index() # pd.DataFrame(TerminalServices_Summary[0])
Terminal_Services_Summary.columns = ['User', 'Authentication Counts']
#Logon_Events_pd=pd.DataFrame(Logon_Events[0])
#Object_Access_Events_pd=pd.DataFrame(Object_Access_Events[0])
#ExecutedProcess_Events_pd=pd.DataFrame(Executed_Process_Events[0])
# allresults=pd.DataFrame([TerminalServices,Powershell_Operational],columns=['Date and Time', 'Detection Rule','Detection Domain','Severity','Event Description','Event ID','Original Event Log'])
allresults = pd.concat(
[ScheduledTask, Powershell_Operational, Sysmon, System, Powershell, Security,TerminalClient, TerminalServices, WinRM,
Windows_Defender,GroupPolicy,SMBServer,SMBClient], join="inner", ignore_index=True)
allresults = allresults.rename(columns={'Date and Time': 'datetime', 'Detection Rule': 'message'})
allresults['timestamp_desc'] = ""
allresults = allresults[
['message','timestamp', 'datetime', 'timestamp_desc', 'Detection Domain', 'Severity', 'Event Description', 'Event ID',
'Original Event Log','Computer Name','Channel']]
Result_Summary_Severity=allresults["Severity"].value_counts().reset_index()
Result_Summary_Severity.columns = ['Severity', 'Counts']
Result_Summary_Detections=allresults["message"].value_counts().reset_index()
Result_Summary_Detections.columns = ['Detection', 'Counts']
allresults.to_csv(timesketch, index=False)
User_SIDs.to_csv(Collected_SIDs, index=False)
print("Time Sketch Report saved as "+timesketch)
#Logon_Events_pd.to_csv(LogonEvents, index=False)
if (logons==True or allreport==True):
print("Logon Events Report saved as "+LogonEvents)
#Object_Access_Events_pd.to_csv(ObjectAccess, index=False)
if (objectaccess==True or allreport==True):
print("Object Access Events Report saved as "+ObjectAccess)
#ExecutedProcess_Events_pd.to_csv(ProcessEvents, index=False)
if (processexec==True or allreport==True):
print("Process Execution Events Report saved as "+ProcessEvents)
# Sysmon=Sysmon.reset_index()
# Sysmon=Sysmon.drop(['index'],axis=1)
writer = pd.ExcelWriter(Report, engine='xlsxwriter', engine_kwargs={'options':{'encoding': 'utf-8'}})
Result_Summary_Severity.to_excel(writer, sheet_name='Result Summary', index=False)
Result_Summary_Detections.to_excel(writer, sheet_name='Result Summary' , startrow=len(Result_Summary_Severity)+3, index=False)
System.to_excel(writer, sheet_name='System Events', index=False)
Powershell.to_excel(writer, sheet_name='Powershell Events', index=False)
Powershell_Operational.to_excel(writer, sheet_name='Powershell_Operational Events', index=False)
Sysmon.to_excel(writer, sheet_name='Sysmon Events', index=False)
Security.to_excel(writer, sheet_name='Security Events', index=False)
TerminalServices.to_excel(writer, sheet_name='TerminalServices Events', index=False)
TerminalClient.to_excel(writer, sheet_name='RDP Client Events', index=False)
WinRM.to_excel(writer, sheet_name='WinRM Events', index=False)
Windows_Defender.to_excel(writer, sheet_name='Windows_Defender Events', index=False)
ScheduledTask.to_excel(writer, sheet_name='ScheduledTask Events', index=False)
GroupPolicy.to_excel(writer, sheet_name='Group Policy Events', index=False)
SMBClient.to_excel(writer, sheet_name='SMB Client Events', index=False)
SMBServer.to_excel(writer, sheet_name='SMB Server Events', index=False)
Terminal_Services_Summary.to_excel(writer, sheet_name='Terminal Services Logon Summary', index=False)
Authentication_Summary.to_excel(writer, sheet_name='Security Authentication Summary', index=False)
ExecutedProcess_Summary.to_excel(writer, sheet_name='Executed Process Summary', index=False)
ExecutedPowershell_Summary.to_excel(writer, sheet_name='Executed Powershell Summary', index=False)
User_SIDs.to_excel(writer, sheet_name='Collected User SIDs', index=False)
writer.book.use_zip64()
writer.close()
print("Report saved as "+Report)
################################################################################################################
# if (frequencyanalysis==True or allreport==True):
# Frequency_Security=pd.DataFrame(list(Frequency_Analysis_Security.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_Defender=pd.DataFrame(list(Frequency_Analysis_Windows_Defender.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_SMB_Client=pd.DataFrame(list(Frequency_Analysis_SMB_Client.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_Group_Policy=pd.DataFrame(list(Frequency_Analysis_Group_Policy.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_Powershell_Operational=pd.DataFrame(list(Frequency_Analysis_Powershell_Operational.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_Powershell=pd.DataFrame(list(Frequency_Analysis_Powershell.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_ScheduledTask=pd.DataFrame(list(Frequency_Analysis_ScheduledTask.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_WinRM=pd.DataFrame(list(Frequency_Analysis_WinRM.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_Sysmon=pd.DataFrame(list(Frequency_Analysis_Sysmon.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_SMB_Server=pd.DataFrame(list(Frequency_Analysis_SMB_Server.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_TerminalServices=pd.DataFrame(list(Frequency_Analysis_TerminalServices.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
# Frequency_System=pd.DataFrame(list(Frequency_Analysis_System.items()),columns=["EventID","Count"]).sort_values(by=['Count'],ascending=False)
#
# writer = pd.ExcelWriter("EventID_Frequency_Analysis.xls", engine='xlsxwriter', options={'encoding': 'utf-8'})
# Frequency_System.to_excel(writer, sheet_name='System', index=False)
# Frequency_Powershell.to_excel(writer, sheet_name='Powershell', index=False)
# Frequency_Powershell_Operational.to_excel(writer, sheet_name='Powershell_Operational', index=False)
# Frequency_Sysmon.to_excel(writer, sheet_name='Sysmon', index=False)
# Frequency_Security.to_excel(writer, sheet_name='Security', index=False)
# Frequency_TerminalServices.to_excel(writer, sheet_name='TerminalServices', index=False)
# Frequency_WinRM.to_excel(writer, sheet_name='WinRM', index=False)
# Frequency_Defender.to_excel(writer, sheet_name='Windows_Defender', index=False)
# Frequency_ScheduledTask.to_excel(writer, sheet_name='ScheduledTask', index=False)
# Frequency_Group_Policy.to_excel(writer, sheet_name='Group Policy', index=False)
# Frequency_SMB_Client.to_excel(writer, sheet_name='SMB Client', index=False)
# Frequency_SMB_Server.to_excel(writer, sheet_name='SMB Server', index=False)
#
# writer.book.use_zip64()
# writer.save()
#
# print("Frequency Analysis Report saved as "+"EventID_Frequency_Analysis.xls")
##################################################################################################################
print("Detection Summary :\n############################################\nNumber of incidents by Severity:\n"+allresults["Severity"].value_counts().to_string()+"\n############################################\nNumber of incidents by Detection Rule:\n"+allresults["message"].value_counts().to_string()+"\n\n")
def convert_list():
global timestart,timeend,User_SIDs,SMB_Server_events,SMB_Client_events,TerminalServices_RDPClient_events,Executed_Process_Events,Group_Policy_events,Object_Access_Events,input_timezone,Logon_Events,Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,Timesketch_events,TerminalServices_Summary,Security_Authentication_Summary,Executed_Powershell_Summary
Results=[Executed_Powershell_Summary,SMB_Server_events,User_SIDs,SMB_Client_events,TerminalServices_RDPClient_events,Executed_Process_Events,Group_Policy_events,Object_Access_Events,Logon_Events,Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,TerminalServices_Summary,Security_Authentication_Summary
]
for result in Results:
for i in result[0]:
result[0][i]=list(result[0][i])
def resolveSID():
global TerminalServices_RDPClient_events,WinRM_events,User_SIDs,RDPClient_Resolved_User,WinRM_Resolved_User
if os.path.exists(temp_dir + "_WinRM_events_report.csv"):
WinRM_events[0] = pd.DataFrame(pd.read_csv(temp_dir + "_WinRM_events_report.csv")).to_dict(orient='list')
if os.path.exists(temp_dir + "_TerminalServices_RDPClient_report.csv"):
TerminalServices_RDPClient_events[0] = pd.DataFrame(pd.read_csv(temp_dir + "_TerminalServices_RDPClient_report.csv")).to_dict(orient='list')
RDPClient_Resolved_User=[]
WinRM_Resolved_User=[]
for SID in TerminalServices_RDPClient_events[0]["UserID"]:
if SID in User_SIDs["SID"]:
RDPClient_Resolved_User.append(User_SIDs["User"][User_SIDs["SID"].index(SID)])
else:
RDPClient_Resolved_User.append("Could not be resolved")
for SID in WinRM_events[0]["UserID"]:
if SID in User_SIDs["SID"]:
WinRM_Resolved_User.append(User_SIDs["User"][User_SIDs["SID"].index(SID)])
else:
WinRM_Resolved_User.append("Could not be resolved")
#print("user sid"+str(User_SIDs["SID"]))
#print("RDPCLient : "+str(RDPClient_Resolved_User))
#print("WinRM : " + str(WinRM_Resolved_User))
def create_temp_dir():
global temp_dir
temp_dir= "temp/"
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
print(f"{temp_dir} has been created")
else:
print(f"{temp_dir} already exists")
def create_out_dir(output):
global temp_dir
if not os.path.exists(output):
os.makedirs(output)
print(f"output folder {output} has been created")
else:
print(f"output folder {output} already exists")
return output+"/"+output
def clean_temp_dir():
global temp_dir
if os.path.exists(temp_dir):
for root, dirs, files in os.walk(temp_dir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(temp_dir)
def main():
tic = time.time()
print(Banner)
global CPU_Core,timestart,timeend,Output,objectaccess,Path,processexec,logons,frequencyanalysis,Security_path,system_path,scheduledtask_path,defender_path,powershell_path,powershellop_path,terminal_path,winrm_path,sysmon_path,input_timezone,objectaccess,processexec,logons,frequencyanalysis,allreport
parser = argparse.ArgumentParser()
parser.add_argument("-p","--path", help="path to folder containing windows event logs , APT-Hunter will detect each log type automatically")
parser.add_argument("-o", "--out",help="output file name")
parser.add_argument("-tz","--timezone", help="default Timezone is Local timezone , you can enter ( 'local' : for local timzone , <Country time zone> : like (Asia/Dubai) )")
parser.add_argument("-o365hunt", "--o365hunt", help="office365 audit log hunting",action='store_true')
parser.add_argument("-o365rules", "--o365rules", help="detection rules for office365 hunt , if not provided default rules will be used")
parser.add_argument("-o365raw", "--o365raw", help="include office365 flattened raw data",action='store_true')
parser.add_argument("-hunt","--hunt", help="String or regex to be searched in evtx log path")
parser.add_argument("-huntfile","--huntfile", help="file contain Strings or regex to be searched in evtx log path ( strings should be new line separated )")
parser.add_argument("-eid","--eid", help="Event ID to search if you chosed the hunt module")
parser.add_argument("-start","--start", help="Start time for timeline ( use ISO format Ex:2022-04-03T20:56+04:00 )")
parser.add_argument("-end","--end", help="End time for timeline ( use ISO format Ex: 2022-04-03T20:56+04:00 or 2022-04-03T20:56 or 2022-04-03 20:56 or 2022-04-03 )")
parser.add_argument("-procexec","--procexec", help="Produce Process Execution report",action='store_true')
parser.add_argument("-logon","--logon", help="Produce Success and faild authentication report",action='store_true')
parser.add_argument("-objaccess","--objaccess", help="Produce Object Access report",action='store_true')
parser.add_argument("-allreport","--allreport", help="Produce all reports",action='store_true')
parser.add_argument("-sigma","--sigma", help="use sigma module to search logs using sigma rules",action='store_true')
parser.add_argument("-rules","--rules", help="path to sigma rules in json format")
#parser.add_argument("-evtfreq","--evtfreq", help="Produce event ID frequency analysis report",action='store_true')
parser.add_argument("-cores","--cores", help="cpu cores to be used in multiprocessing , default is half the number of availble CPU cores")
args = parser.parse_args()
if args.out is not None:
Output=create_out_dir(args.out)
if (args.path is None ):# and args.security is None and args.system is None and args.scheduledtask is None and args.defender is None and args.powershell is None and args.powershellop is None and args.terminal is None and args.winrm is None and args.sysmon is None):
print("You didn't specify a path for the logs \nuse --help to print help message")
exit()
#if args.type is None and args.hunt is None:
# print("log type must be defined using -t \ncsv( logs from get-eventlog or windows event log GUI or logs from Get-WinEvent ) , evtx ( EVTX extension windows event log )\nuse --help to print help message")
# exit()
else:
#if args.path is not None:
Path=args.path
objectaccess=args.objaccess
processexec=args.procexec
logons=args.logon
#frequencyanalysis=args.evtfreq
allreport=args.allreport
CPU_Core=0
#print(f"all reports value : {allreport}\nlogons value {logons}")
try:
if args.start is not None and args.end is not None:
timestart=datetime.timestamp(dateutil.parser.isoparse(args.start))
timeend=datetime.timestamp(dateutil.parser.isoparse(args.end))
except:
print("Error parsing time , please use ISO format with timestart and timeend Ex: (2022-04-03T20:56+04:00 or 2022-04-03T20:56 or 2022-04-03 20:56 or 2022-04-03)")
exit()
if args.timezone is not None:
if args.timezone.lower()=="local":
input_timezone=tz.tzlocal()
else:
input_timezone=timezone(args.timezone)
if args.cores is not None:
try:
CPU_Core=int(args.cores)
except:
print(f"Error using supplied CPU cores {args.cores}")
exit(0)
if args.sigma is not False:
if args.rules is not None:
SigmaHunter.Sigma_Analyze(Path,args.rules,Output)
else:
print("Please include rules path ex : --rules rules.json")
toc = time.time()
print('Done in {:.4f} seconds'.format(toc-tic))
return
if args.hunt is not None:
if args.eid is not None:
threat_hunt(Path,args.hunt,args.eid,None)
else:
threat_hunt(Path,args.hunt,None,None)
toc = time.time()
print('Done in {:.4f} seconds'.format(toc-tic))
return
if args.o365hunt is not False:
if args.o365rules is not None:
O365Hunter.analyzeoff365(Path, args.o365rules,Output,input_timezone,args.o365raw)
else:
O365Hunter.analyzeoff365(Path, None,Output,input_timezone,args.o365raw)
#toc = time.time()
#print('Done in {:.4f} seconds'.format(toc-tic))
return
if args.hunt is None and args.huntfile is not None:
if args.eid is not None:
threat_hunt(Path,None,args.eid,args.huntfile)
else:
threat_hunt(Path,None,None,args.huntfile)
toc = time.time()
print('Done in {:.4f} seconds'.format(toc-tic))
return
#if args.type is None or args.type=="evtx":
try:
create_temp_dir()
auto_detect(Path)
#convert_list()
report()
clean_temp_dir()
except Exception as e:
print("Error "+str(e))
clean_temp_dir()
toc = time.time()
print('Analysis finished in {:.4f} seconds'.format(toc-tic))
return
if __name__ == '__main__':
if platform.system().lower()=="windows":
multiprocessing.freeze_support()
main()

@ -1,557 +0,0 @@
import traceback
import logging
from lib.Banner import *
import argparse
import pandas as pd
import lib.EvtxDetection as EvtxDetection
import lib.CSVDetection as CSVDetection
import lib.EvtxHunt as EvtxHunt
from evtx import PyEvtxParser
from sys import exit
from pytz import timezone
from dateutil import tz
import glob
import os
import re
Output=""
Path=""
Security_path=""
system_path=""
scheduledtask_path=""
defender_path=""
powershell_path=""
powershellop_path=""
terminal_path=""
winrm_path=""
sysmon_path=""
Security_path_list=[]
system_path_list=[]
scheduledtask_path_list=[]
defender_path_list=[]
powershell_path_list=[]
powershellop_path_list=[]
terminal_path_list=[]
winrm_path_list=[]
sysmon_path_list=[]
input_timezone=timezone("UTC")
Logon_Events=[{'Date and Time':[],'timestamp':[],'Event ID':[],'Account Name':[],'Account Domain':[],'Logon Type':[],'Logon Process':[],'Source IP':[],'Workstation Name':[],'Original Event Log':[]}]
Executed_Process_Summary=[{'Process Name':[],'Number of Execution':[]}]
TerminalServices_Summary=[{'User':[],'Number of Logins':[]}]
Security_Authentication_Summary=[{'User':[],'Number of Failed Logins':[],'Number of Successful Logins':[]}]
Sysmon_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
WinRM_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
Security_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
System_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Service Name':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
ScheduledTask_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Schedule Task Name':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
Powershell_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
Powershell_Operational_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
TerminalServices_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
Windows_Defender_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
Timesketch_events=[{'message':[],'timestamp':[],'datetime':[],'timestamp_desc':[],'Event Description':[],'Severity':[],'Detection Domain':[],'Event ID':[],'Original Event Log':[]}]
def evtxdetect():
global input_timezone,Logon_Events,Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,Timesketch_events,TerminalServices_Summary,Security_Authentication_Summary
try:
print(Security_path)
EvtxDetection.detect_events_security_log(Security_path,input_timezone)
except IOError :
print("Error Analyzing Security logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Security logs")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_system_log(system_path,input_timezone)
except IOError :
print("Error Analyzing System logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing System logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_powershell_operational_log(powershellop_path,input_timezone)
except IOError :
print("Error Analyzing Powershell Operational logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell Operational logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_powershell_log(powershell_path,input_timezone)
except IOError :
print("Error Analyzing Powershell logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_TerminalServices_LocalSessionManager_log(terminal_path,input_timezone)
except IOError :
print("Error Analyzing TerminalServices LocalSessionManager logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing TerminalServices LocalSessionManager logs")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_scheduled_task_log(scheduledtask_path,input_timezone)
except IOError :
print("Error Analyzing Scheduled Task logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Scheduled Task logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_windows_defender_log(defender_path,input_timezone)
except IOError :
print("Error Analyzing Windows Defender logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Windows Defender logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_Microsoft_Windows_WinRM(winrm_path,input_timezone)
except IOError :
print("Error Analyzing WinRM logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing WinRM logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_Sysmon_log(sysmon_path,input_timezone)
except IOError :
print("Error Analyzing Sysmon logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Sysmon logs ")
logging.error(traceback.format_exc())
Sysmon_events = EvtxDetection.Sysmon_events
WinRM_events =EvtxDetection.WinRM_events
Security_events =EvtxDetection.Security_events
System_events =EvtxDetection.System_events
ScheduledTask_events =EvtxDetection.ScheduledTask_events
Powershell_events =EvtxDetection.Powershell_events
Powershell_Operational_events =EvtxDetection.Powershell_Operational_events
TerminalServices_events =EvtxDetection.TerminalServices_events
Windows_Defender_events =EvtxDetection.Windows_Defender_events
Timesketch_events =EvtxDetection.Timesketch_events
TerminalServices_Summary=EvtxDetection.TerminalServices_Summary
Executed_Process_Summary=EvtxDetection.Executed_Process_Summary
Security_Authentication_Summary =EvtxDetection.Security_Authentication_Summary
Logon_Events =EvtxDetection.Logon_Events
def csvdetect(winevent):
global Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,Timesketch_events,TerminalServices_Summary,Security_Authentication_Summary
try:
#print(Security_path,winevent)
CSVDetection.detect_events_security_log(Security_path,winevent)
except IOError :
print("Error Analyzing Security logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Security logs")
logging.error(traceback.format_exc())
try:
CSVDetection.detect_events_system_log(system_path,winevent)
except IOError :
print("Error Analyzing System logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing System logs ")
logging.error(traceback.format_exc())
try :
CSVDetection.detect_events_powershell_operational_log(powershellop_path,winevent)
except IOError :
print("Error Analyzing Powershell Operational logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell Operational logs ")
logging.error(traceback.format_exc())
try :
CSVDetection.detect_events_powershell_log(powershell_path,winevent)
except IOError :
print("Error Analyzing Powershell logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell logs ")
logging.error(traceback.format_exc())
try :
CSVDetection.detect_events_TerminalServices_LocalSessionManager_log(terminal_path,winevent)
except IOError :
print("Error Analyzing TerminalServices LocalSessionManager logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing TerminalServices LocalSessionManager logs")
logging.error(traceback.format_exc())
try:
CSVDetection.detect_events_scheduled_task_log(scheduledtask_path,winevent)
except IOError :
print("Error Analyzing Scheduled Task logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Scheduled Task logs ")
logging.error(traceback.format_exc())
try:
CSVDetection.detect_events_windows_defender_log(defender_path,winevent)
except IOError :
print("Error Analyzing Windows Defender logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Windows Defender logs ")
logging.error(traceback.format_exc())
try:
CSVDetection.detect_events_Microsoft_Windows_WinRM_CSV_log(winrm_path,winevent)
except IOError :
print("Error Analyzing WinRM logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing WinRM logs ")
logging.error(traceback.format_exc())
try:
CSVDetection.detect_events_Sysmon_log(sysmon_path,winevent)
except IOError :
print("Error Analyzing Sysmon logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Sysmon logs ")
logging.error(traceback.format_exc())
Sysmon_events = CSVDetection.Sysmon_events
WinRM_events =CSVDetection.WinRM_events
Security_events =CSVDetection.Security_events
System_events =CSVDetection.System_events
ScheduledTask_events =CSVDetection.ScheduledTask_events
Powershell_events =CSVDetection.Powershell_events
Powershell_Operational_events =CSVDetection.Powershell_Operational_events
TerminalServices_events =CSVDetection.TerminalServices_events
Windows_Defender_events =CSVDetection.Windows_Defender_events
Timesketch_events =CSVDetection.Timesketch_events
TerminalServices_Summary=CSVDetection.TerminalServices_Summary
Executed_Process_Summary=CSVDetection.Executed_Process_Summary
Security_Authentication_Summary =CSVDetection.Security_Authentication_Summary
def evtxdetect_auto():
global input_timezone,Logon_Events,Executed_Process_Summary,TerminalServices_Summary,Security_Authentication_Summary,Sysmon_events,WinRM_events,Security_events,System_events,ScheduledTask_events,Powershell_events,Powershell_Operational_events,TerminalServices_events,Windows_Defender_events,Timesketch_events,TerminalServices_Summary,Security_Authentication_Summary
try:
#print(Security_path)
EvtxDetection.detect_events_security_log(Security_path_list,input_timezone)
except IOError :
print("Error Analyzing Security logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Security logs")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_system_log(system_path_list,input_timezone)
except IOError :
print("Error Analyzing System logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing System logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_powershell_operational_log(powershellop_path_list,input_timezone)
except IOError :
print("Error Analyzing Powershell Operational logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell Operational logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_powershell_log(powershell_path_list,input_timezone)
except IOError :
print("Error Analyzing Powershell logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Powershell logs ")
logging.error(traceback.format_exc())
try :
EvtxDetection.detect_events_TerminalServices_LocalSessionManager_log(terminal_path_list,input_timezone)
except IOError :
print("Error Analyzing TerminalServices LocalSessionManager logs: ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing TerminalServices LocalSessionManager logs")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_scheduled_task_log(scheduledtask_path_list,input_timezone)
except IOError :
print("Error Analyzing Scheduled Task logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Scheduled Task logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_windows_defender_log(defender_path_list,input_timezone)
except IOError :
print("Error Analyzing Windows Defender logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Windows Defender logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_Microsoft_Windows_WinRM(winrm_path_list,input_timezone)
except IOError :
print("Error Analyzing WinRM logs : ", end='')
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing WinRM logs ")
logging.error(traceback.format_exc())
try:
EvtxDetection.detect_events_Sysmon_log(sysmon_path_list,input_timezone)
except IOError :
print("Error Analyzing Sysmon logs ")
print("File Path Does Not Exist")
except Exception as e:
print("Error Analyzing Sysmon logs ")
logging.error(traceback.format_exc())
Sysmon_events = EvtxDetection.Sysmon_events
WinRM_events =EvtxDetection.WinRM_events
Security_events =EvtxDetection.Security_events
System_events =EvtxDetection.System_events
ScheduledTask_events =EvtxDetection.ScheduledTask_events
Powershell_events =EvtxDetection.Powershell_events
Powershell_Operational_events =EvtxDetection.Powershell_Operational_events
TerminalServices_events =EvtxDetection.TerminalServices_events
Windows_Defender_events =EvtxDetection.Windows_Defender_events
Timesketch_events =EvtxDetection.Timesketch_events
TerminalServices_Summary=EvtxDetection.TerminalServices_Summary
Executed_Process_Summary=EvtxDetection.Executed_Process_Summary
Security_Authentication_Summary =EvtxDetection.Security_Authentication_Summary
Logon_Events =EvtxDetection.Logon_Events
def auto_detect(path):
global input_timezone
EventID_rex = re.compile('<EventID.*>(.*)<\/EventID>', re.IGNORECASE)
Channel_rex = re.compile('<Channel.*>(.*)<\/Channel>', re.IGNORECASE)
Computer_rex = re.compile('<Computer.*>(.*)<\/Computer>', re.IGNORECASE)
if os.path.isdir(path):
files=glob.glob(path+"*.evtx")
elif os.path.isfile(path):
files=glob.glob(path)
else:
print("Issue with the path" )
return
#print("hunting ( %s ) in files ( %s )"%(str_regex,files))
#user_string = input('please enter a string to convert to regex: ')
for file in files:
print("Analyzing "+file)
try:
parser = PyEvtxParser(file)
except:
print("Issue analyzing "+file +"\nplease check if its not corrupted")
continue
try:
for record in parser.records():
Channel = Channel_rex.findall(record['data'])
if Channel[0].strip()=="Security":
Security_path_list.append(file)
break
if Channel[0].strip()=="System":
system_path_list.append(file)
break
if Channel[0].strip()=="Windows PowerShell":
powershell_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-PowerShell/Operational":
powershellop_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-TerminalServices-LocalSessionManager/Operational":
terminal_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-TaskScheduler/Operational":
scheduledtask_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-Windows Defender/Operational":
defender_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-WinRM/Operational":
winrm_path_list.append(file)
break
if Channel[0].strip()=="Microsoft-Windows-Sysmon/Operational":
sysmon_path_list.append(file)
break
break
except:
print("issue assigning path")
evtxdetect_auto()
def threat_hunt(path,str_regex):
global input_timezone, Output
import os
if os.path.isdir(path):
files=glob.glob(path+"*.evtx")
elif os.path.isfile(path):
files=glob.glob(path)
else:
print("Issue with the path" )
return
print("hunting ( %s ) in files ( %s )"%(str_regex,files))
#user_string = input('please enter a string to convert to regex: ')
EvtxHunt.Evtx_hunt(files,str_regex,input_timezone,Output)
def report():
global Output
timesketch=Output+"_TimeSketch.csv"
Report=Output+"_Report.xlsx"
LogonEvents=Output+"_Logon_Events.csv"
Sysmon = pd.DataFrame(Sysmon_events[0])
System = pd.DataFrame(System_events[0])
Powershell = pd.DataFrame(Powershell_events[0])
Powershell_Operational = pd.DataFrame(Powershell_Operational_events[0])
Security = pd.DataFrame(Security_events[0])
TerminalServices = pd.DataFrame(TerminalServices_events[0])
WinRM = pd.DataFrame(WinRM_events[0])
Windows_Defender = pd.DataFrame(Windows_Defender_events[0])
ScheduledTask = pd.DataFrame(ScheduledTask_events[0])
Terminal_Services_Summary = pd.DataFrame(TerminalServices_Summary[0])
Authentication_Summary = pd.DataFrame(Security_Authentication_Summary[0])
ExecutedProcess_Summary=pd.DataFrame(Executed_Process_Summary[0])
Logon_Events_pd=pd.DataFrame(Logon_Events[0])
# allresults=pd.DataFrame([TerminalServices,Powershell_Operational],columns=['Date and Time', 'Detection Rule','Detection Domain','Severity','Event Description','Event ID','Original Event Log'])
allresults = pd.concat(
[ScheduledTask, Powershell_Operational, Sysmon, System, Powershell, Security, TerminalServices, WinRM,
Windows_Defender], join="inner", ignore_index=True)
allresults = allresults.rename(columns={'Date and Time': 'datetime', 'Detection Rule': 'message'})
allresults['timestamp_desc'] = ""
allresults = allresults[
['message','timestamp', 'datetime', 'timestamp_desc', 'Detection Domain', 'Severity', 'Event Description', 'Event ID',
'Original Event Log']]
allresults.to_csv(timesketch, index=False)
print("Time Sketch Report saved as "+timesketch)
Logon_Events_pd.to_csv(LogonEvents, index=False)
# Sysmon=Sysmon.reset_index()
# Sysmon=Sysmon.drop(['index'],axis=1)
writer = pd.ExcelWriter(Report, engine='xlsxwriter', options={'encoding': 'utf-8'})
System.to_excel(writer, sheet_name='System Events', index=False)
Powershell.to_excel(writer, sheet_name='Powershell Events', index=False)
Powershell_Operational.to_excel(writer, sheet_name='Powershell_Operational Events', index=False)
Sysmon.to_excel(writer, sheet_name='Sysmon Events', index=False)
Security.to_excel(writer, sheet_name='Security Events', index=False)
TerminalServices.to_excel(writer, sheet_name='TerminalServices Events', index=False)
WinRM.to_excel(writer, sheet_name='WinRM Events', index=False)
Windows_Defender.to_excel(writer, sheet_name='Windows_Defender Events', index=False)
ScheduledTask.to_excel(writer, sheet_name='ScheduledTask Events', index=False)
Terminal_Services_Summary.to_excel(writer, sheet_name='Terminal Services Logon Summary', index=False)
Authentication_Summary.to_excel(writer, sheet_name='Security Authentication Summary', index=False)
ExecutedProcess_Summary.to_excel(writer, sheet_name='Executed Process Summary', index=False)
writer.save()
print("Report saved as "+Report)
def main():
print(Banner)
global Output,Path,Security_path,system_path,scheduledtask_path,defender_path,powershell_path,powershellop_path,terminal_path,winrm_path,sysmon_path,input_timezone
parser = argparse.ArgumentParser()
parser.add_argument("-p","--path", help="path to folder containing windows event logs generated by the powershell log collector")
parser.add_argument("-o", "--out",
help="output file name")
parser.add_argument("-t","--type", help="csv ( logs from get-eventlog or windows event log GUI or logs from Get-WinEvent ) , evtx ( EVTX extension windows event log )",choices=["csv","evtx"])
parser.add_argument("--security", help="Path to Security Logs")
parser.add_argument("--system", help="Path to System Logs")
parser.add_argument("--scheduledtask", help="Path to Scheduled Tasks Logs")
parser.add_argument("--defender", help="Path to Defender Logs")
parser.add_argument("--powershell", help="Path to Powershell Logs")
parser.add_argument("--powershellop", help="Path to Powershell Operational Logs")
parser.add_argument("--terminal", help="Path to TerminalServices LocalSessionManager Logs")
parser.add_argument("--winrm", help="Path to Winrm Logs")
parser.add_argument("--sysmon", help="Path to Sysmon Logs")
parser.add_argument("-tz","--timezone", help="default Timezone is UTC , you can enter ( 'local' : for local timzone , <Country time zone> : like (Asia/Dubai) )")
parser.add_argument("-hunt","--hunt", help="String or regex to be searched in evtx log path")
args = parser.parse_args()
if args.out is not None:
Output=args.out
if (args.path is None and args.security is None and args.system is None and args.scheduledtask is None and args.defender is None and args.powershell is None and args.powershellop is None and args.terminal is None and args.winrm is None and args.sysmon is None):
print("You didn't specify a path for any log \nuse --help to print help message")
exit()
if args.type is None and args.hunt is None:
print("log type must be defined using -t \ncsv( logs from get-eventlog or windows event log GUI or logs from Get-WinEvent ) , evtx ( EVTX extension windows event log )\nuse --help to print help message")
exit()
else:
if args.path is not None:
Path=args.path
if args.hunt is not None:
threat_hunt(Path,args.hunt)
return
if args.type=="evtx":
Security_path=Path+"/Security.evtx"
system_path =Path+"/System.evtx"
scheduledtask_path = Path+"/TaskScheduler.evtx"
defender_path = Path+"/Windows_Defender.evtx"
powershell_path = Path+"/Windows_PowerShell.evtx"
powershellop_path = Path+"/Powershell_Operational.evtx"
terminal_path = Path+"/LocalSessionManager.evtx"
winrm_path = Path+"/WinRM.evtx"
sysmon_path = Path+"/Sysmon.evtx"
if args.type=="csv":
Security_path=Path+"/Security.csv"
system_path =Path+"/System.csv"
scheduledtask_path = Path+"/TaskScheduler.csv"
defender_path = Path+"/Windows_Defender.csv"
powershell_path = Path+"/Windows_PowerShell.csv"
powershellop_path = Path+"/Powershell_Operational.csv"
terminal_path = Path+"/LocalSessionManager.csv"
winrm_path = Path+"/WinRM.csv"
sysmon_path = Path+"/Sysmon.csv"
if args.security is not None:
Security_path = args.security
if args.system is not None:
system_path=args.system
if args.scheduledtask is not None:
scheduledtask_path=args.scheduledtask
if args.defender is not None:
defender_path=args.defender
if args.powershell is not None:
powershell_path=args.powershell
if args.powershellop is not None:
powershellop_path=args.powershellop
if args.terminal is not None:
terminal_path=args.terminal
if args.winrm is not None:
winrm_path=args.winrm
if args.sysmon is not None:
sysmon_path=args.sysmon
if args.timezone is not None:
if args.timezone.lower()=="local":
input_timezone=tz.tzlocal()
else:
input_timezone=timezone(args.timezone)
if args.type=="evtx":
#evtxdetect()
auto_detect(Path)
if args.type=="csv":
csvdetect(True)
report()
main()

@ -1,15 +0,0 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Please enter rules path as argument "
exit 1
fi
echo "Getting Sigma Converter Toot"
git clone https://github.com/SigmaHQ/legacy-sigmatools.git
echo "Converting sigma rules "
legacy-sigmatools/tools/sigmac --recurse --target sqlite --backend-option table=Events --output-format json -d $1 -c lib/config/sigma-converter-rules-config.yml -o rules.json --output-fields title,id,description,author,tags,level,falsepositives,filename,status
echo "Rules created with file name : rules.json "

@ -1,11 +0,0 @@
#!/bin/bash
echo "Getting Sigma Converter Toot"
git clone https://github.com/SigmaHQ/legacy-sigmatools.git
echo "Getting Sigma Rules"
git clone https://github.com/SigmaHQ/sigma.git
echo "Converting sigma rules "
legacy-sigmatools/tools/sigmac --recurse --target sqlite --backend-option table=Events --output-format json -d sigma/rules/windows/ -c lib/config/sigma-converter-rules-config.yml -o rules.json --output-fields title,id,description,author,tags,level,falsepositives,filename,status
echo "Rules created with file name : rules.json "

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

@ -1,99 +0,0 @@
[
{
"name": "Suspicious User Agent",
"severity": "High",
"query": "SELECT * FROM events WHERE UserAgent LIKE '%python%' OR UserAgent LIKE '%ruler%' OR UserAgent LIKE '%curl%' OR UserAgent LIKE '%Wget%' OR UserAgent LIKE '%python-requests%' OR UserAgent LIKE '%AADInternals%' OR UserAgent LIKE '%azurehound%' OR UserAgent LIKE '%axios%' OR UserAgent LIKE '%BAV2ROPC%' "
},
{
"name": "User adding or removing Inbox Rule",
"severity": "Medium",
"query": "SELECT * FROM events WHERE Operation LIKE '%InboxRule%' OR Operation LIKE 'Set-Mailbox' OR Operation LIKE '%DeliverToMailboxAndForward%' OR Operation LIKE '%ForwardingAddress%' OR Operation LIKE '%ForwardingAddress%' "
},
{
"name": "After Hours Activity",
"severity": "Medium",
"query": "SELECT * FROM events WHERE (CASE WHEN CAST(substr(CreationTime, 12, 2) AS INTEGER) < 0 THEN 24 + (CAST(substr(CreationTime, 12, 2) AS INTEGER)) ELSE CAST(substr(CreationTime, 12, 2) AS INTEGER) END >= 20 OR CASE WHEN CAST(substr(CreationTime, 12, 2) AS INTEGER) < 0 THEN 24 + (CAST(substr(CreationTime, 12, 2) AS INTEGER)) ELSE CAST(substr(CreationTime, 12, 2) AS INTEGER) END < 6) AND NOT (Operation LIKE 'File%' OR Operation LIKE 'List%' OR Operation LIKE 'Page%' OR Operation LIKE '%UserLogin%');"
},
{
"name": "Possible file exfiltration",
"severity": "Low",
"query": "SELECT * FROM events WHERE Operation LIKE '%FileUploaded%' "
},
{
"name": "Admin searching in emails of other users",
"severity": "Low",
"query": "SELECT * FROM events WHERE Operation LIKE '%SearchStarted%' OR Operation LIKE '%SearchExportDownloaded%' OR Operation LIKE '%ViewedSearchExported%' "
},
{
"name": "Strong Authentication Disabled",
"severity": "medium",
"query": "SELECT * FROM events WHERE Operation LIKE '%disable strong authentication%'"
},
{
"name": "User added to admin group",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%add member to group%' AND ModifiedProperties Like '%admin%') OR ( Operation LIKE '%AddedToGroup%' AND TargetUserOrGroupName Like '%admin%') "
},
{
"name": "New Policy created",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%add policy%' ) "
},
{
"name": "Security Alert triggered",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%AlertTriggered%' AND NOT Severity Like '%Low%') "
},
{
"name": "Transport rules ( mail flow rules ) modified",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%TransportRule%') "
},
{
"name": "An application was registered in Azure AD",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%Add service principal.%') "
},
{
"name": "Add app role assignment grant to user",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%Add app role assignment grant to user.%') "
},
{
"name": "eDiscovery Abuse",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%New-ComplianceSearch%') "
},
{
"name": "Operations affecting OAuth Applications",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation = 'Add application.' OR Operation = 'Update application' OR Operation = 'Add service principal.' OR Operation = 'Update application Certificates and secrets management' OR Operation = 'Update applicationUpdate service principal.' OR Operation = 'Add app role assignment grant to user.' OR Operation = 'Add delegated permission grant.' OR Operation = 'Add owner to application.' OR Operation = 'Add owner to service principal.') "
},
{
"name": "Suspicious Operations affecting Mailbox ",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation = 'Set-MailboxJunkEmailConfiguration' OR Operation = 'SoftDelete' OR Operation = 'SendAs' OR Operation = 'HardDelete' OR Operation = 'MoveToDeletedItems' ) "
},
{
"name": "Suspicious Operations affecting SharePoint ",
"severity": "Medium",
"query": "SELECT * FROM events WHERE ( Operation = 'AddedToSecureLink' OR Operation = 'SearchQueryPerformed' OR Operation = 'SecureLinkCreated' OR Operation = 'SecureLinkUpdated' OR Operation = 'SharingInvitationCreated' ) "
},
{
"name": "User Modifying RetentionPolicy ",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%UnifiedAuditLogRetentionPolicy%' ) "
},
{
"name": "User Modifying Audit Logging ",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%AdminAuditLogConfig%' ) "
},
{
"name": "String Authentication Disabled ",
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%Disable Strong Authentication.%' ) "
}
]

@ -1,99 +0,0 @@
<p align="center">
<a href="https://github.com/ahmedkhlief/APT-Hunter/releases"><img src="https://img.shields.io/github/v/release/ahmedkhlief/APT-Hunter?color=blue&label=Stable%20Version&style=flat""/></a>
<a href="https://github.com/ahmedkhlief/APT-Hunter/releases"><img src="https://img.shields.io/github/downloads/ahmedkhlief/APT-Hunter/total?style=flat&label=GitHub Downloads&color=blue"/></a>
<a href="https://github.com/ahmedkhlief/APT-Hunter/stargazers"><img src="https://img.shields.io/github/stars/ahmedkhlief/APT-Hunter?style=flat&label=GitHub Stars"/></a>
<a href="https://github.com/ahmedkhlief/APT-Hunter/graphs/contributors"><img src="https://img.shields.io/github/contributors/ahmedkhlief/APT-Hunter?label=Contributors&color=blue&style=flat"/></a>
</p>
# APT-Hunter
APT-Hunter is Threat Hunting tool for windows event logs which made by purple team mindset to detect APT movements hidden in the sea of windows event logs to decrease the time to uncover suspicious activity . APT-Hunter use pre-defined detection rules and focus on statistics to uncover abnormalities which is very effective in compromise assessment . the output produced with timeline that can be analyzed directly from Excel , Timeline Explorer , Timesketch , etc...
Full information about the tool and how its used in this article : [introducing-apt-hunter-threat-hunting-tool-using-windows-event-log](https://shells.systems/introducing-apt-hunter-threat-hunting-tool-via-windows-event-log/)
New Release Info : [APT-HUNTER V3.0 : Rebuilt with Multiprocessing and new cool features](https://shells.systems/apt-hunter-v3-0-rebuilt-with-multiprocessing-and-new-cool-features/)
# Author
Twitter : [@ahmed_khlief](https://twitter.com/ahmed_khlief)
Linkedin : [Ahmed Khlief](https://www.linkedin.com/in/ahmed-khlief-499321a7)
# Donwload APT-Hunter :
Download the latest stable version of APT-Hunter with compiled binaries from [Releases](https://github.com/ahmedkhlief/APT-Hunter/releases) page.
# How to Use APT-Hunter
APT-Hunter built using python3 so in order to use the tool you need to install the required libraries.
`python3 -m pip install -r requirements.txt`
APT-Hunter is easy to use you just use the argument -h to print help to see the options needed .
` python3 APT-Hunter.py -h`
![APT-Hunter Help](screenshots/APTHunter-Help.png)
![APT-Hunter Analyzing with all report ](screenshots/APTHunter-Allreport.png)
![APT-Hunter commandline output ](screenshots/APTHunter-output.png)
![APT-Hunter Excel Output ](screenshots/APTHunter-Excel.png)
![APT-Hunter CSV Output with Time Sketch](screenshots/APTHunter-Timeline-Explorer.png)
# Exmaples :
Analyzing EVTX files , you can provide directory containing the logs or single file , APT hunter will detect the type of logs .
`python3 APT-Hunter.py -p /opt/wineventlogs/ -o Project1 -allreport`
Adding time frame to focus on specific timeline :
`python3 APT-Hunter.py -p /opt/wineventlogs/ -o Project1 -allreport -start 2022-04-03 -end 2022-04-05T20:56`
Hunting using String or regex :
`python3 APT-Hunter.py -hunt "psexec" -p /opt/wineventlogs/ -o Project2`
`python3 APT-Hunter.py -huntfile "(psexec|psexesvc)" -p /opt/wineventlogs/ -o Project2`
hunting using file that contain list of regex :
`python3 APT-Hunter.py -huntfile "huntfile.txt)" -p /opt/wineventlogs/ -o Project2`
Hunting using sigma rules :
`python3 APT-Hunter.py -sigma -rules rules.json -p /opt/wineventlogs/ -o Project2`
Getting Latest sigma rules converted for APT-Hunter ( output will be a file with name rules.json that contain the rules from Sigma repository [Sigma](https://github.com/SigmaHQ/sigma) ):
Get_Latest_Sigma_Rules.sh
# Output Samples
![APT-Hunter CSV Output](Samples/Sample_TimeSketch.csv) : This CSV file you can upload it to timesketch in order to have timeline analysis that will help you see the full picture of the attack .
![APT-Hunter Excel Output](Samples/Sample_Report.xlsx) : this excel sheet will include all the events detected from every windows logs provided to APT-Hunter.
![APT-Hunter Success and Failed logon Report ](Samples/Sample_Logon_Events.csv) : ALl logon events with parsed fields (Date, User , Source IP , Logon Process , Workstation Name , Logon Type , Device Name , Original Log ) as columns.
![APT-Hunter Process Execution Report ](Samples/Sample_Process_Execution_Events.csv) : all process execution captured from the event logs.
![APT-Hunter Object Access Report ](Samples/Sample_Object_Access_Events.csv) : all object access captured from Event (4663) .
![APT-Hunter Collected SID Report ](Samples/Sample_Collected-SIDS.csv) : Collected Users with their SID list to help you in the investigation.
![APT-Hunter EventID Frequency Report ](Samples/EventID_Frequency_Analysis.xls) : EventID frequency analysis report.
# Credits :
I would like to thank [Joe Maccry](https://www.linkedin.com/in/joemccray/) for his amazing contribution in Sysmon use cases ( more than 100 use cases added by Joe )

@ -1,13 +0,0 @@
Banner="""
/$$$$$$ /$$$$$$$ /$$$$$$$$ /$$ /$$ /$$
/$$__ $$| $$__ $$|__ $$__/ | $$ | $$ | $$
| $$ \ $$| $$ \ $$ | $$ | $$ | $$ /$$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$
| $$$$$$$$| $$$$$$$/ | $$ /$$$$$$| $$$$$$$$| $$ | $$| $$__ $$|_ $$_/ /$$__ $$ /$$__ $$
| $$__ $$| $$____/ | $$ |______/| $$__ $$| $$ | $$| $$ \ $$ | $$ | $$$$$$$$| $$ \__/
| $$ | $$| $$ | $$ | $$ | $$| $$ | $$| $$ | $$ | $$ /$$| $$_____/| $$
| $$ | $$| $$ | $$ | $$ | $$| $$$$$$/| $$ | $$ | $$$$/| $$$$$$$| $$
|__/ |__/|__/ |__/ |__/ |__/ \______/ |__/ |__/ \___/ \_______/|__/
By : Ahmed Khlief , @ahmed_khlief
Version : 3.3
"""

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -1,72 +0,0 @@
import csv
import re
from netaddr import *
import xml.etree.ElementTree as ET
import pandas as pd
from datetime import datetime , timezone
from evtx import PyEvtxParser
from dateutil.parser import parse
from dateutil.parser import isoparse
from pytz import timezone
minlength=1000
Hunting_events=[{'Date and Time':[],'timestamp':[],'Channel':[],'Computer':[],'Event ID':[],'Original Event Log':[]}]
EventID_rex = re.compile('<EventID.*>(.*)<\/EventID>', re.IGNORECASE)
Channel_rex = re.compile('<Channel.*>(.*)<\/Channel>', re.IGNORECASE)
Computer_rex = re.compile('<Computer.*>(.*)<\/Computer>', re.IGNORECASE)
def Evtx_hunt(files,str_regexes,eid,input_timzone,output,timestart,timeend):
for file in files:
file=str(file)
print("Analyzing "+file)
try:
parser = PyEvtxParser(file)
except:
print("Issue analyzing "+file +"\nplease check if its not corrupted")
continue
try:
for record in parser.records():
EventID = EventID_rex.findall(record['data'])
if timestart is not None and timeend is not None:
timestamp = datetime.timestamp(isoparse(parse(record["timestamp"]).astimezone(input_timzone).isoformat()))
if not (timestamp > timestart and timestamp < timeend):
return
if len(EventID) > 0:
if eid is not None and EventID[0]!=eid:
continue
Computer = Computer_rex.findall(record['data'])
Channel = Channel_rex.findall(record['data'])
if len(Channel)>0:
channel=Channel[0]
else:
channel=" "
#print(record['data'])
# if record['data'].lower().find(str_regex.lower())>-1:
#print(str_regexes)
for str_regex in str_regexes:
rex=re.compile(str_regex, re.IGNORECASE)
#print(rex)
#print(rex.findall(record['data']))
if rex.findall(record['data']):
#print("EventID : "+EventID[0]+" , Data : "+record['data'])
Hunting_events[0]['timestamp'].append(datetime.timestamp(isoparse(parse(record["timestamp"]).astimezone(input_timzone).isoformat())))
Hunting_events[0]['Date and Time'].append(parse(record["timestamp"]).astimezone(input_timzone).isoformat())
Hunting_events[0]['Channel'].append(channel)
Hunting_events[0]['Event ID'].append(EventID[0])
Hunting_events[0]['Computer'].append(Computer[0])
Hunting_events[0]['Original Event Log'].append(str(record['data']).replace("\r", " ").replace("\n", " "))
except Exception as e:
print("issue searching log : "+record['data']+"\n Error : "+print(e))
hunt_report(output)
def hunt_report(output):
global Hunting_events
Events = pd.DataFrame(Hunting_events[0])
print("Found "+str(len(Hunting_events[0]["timestamp"]))+" Events")
Events.to_csv(output+"_hunting.csv", index=False)

@ -1,321 +0,0 @@
import json
import sqlite3
import tempfile
import os
import time
import pandas as pd
import geoip2.database
import requests
from dateutil import parser, tz
import pandas as pd
import json
import csv
from pathlib import Path
start_time=0
end_time=0
password_spray_query = '''
WITH FailedLogins AS (
SELECT
UserId,
ClientIP,
datetime(CreationTime) AS LoginDate
FROM
events
WHERE
Operation = 'UserLoginFailed'
)
SELECT
UserId,
GROUP_CONCAT(ClientIP, ', ') AS ClientIPs,
COUNT(DISTINCT ClientIP) AS UniqueIPCount,
COUNT(*) AS FailedLoginAttempts,
LoginDate
FROM
FailedLogins
GROUP BY
UserId,
strftime('%Y-%m-%d %H', LoginDate)
HAVING
COUNT(*) > 5 AND UniqueIPCount > 3
ORDER BY
FailedLoginAttempts DESC;
'''
user_logon_query = '''
SELECT
UserId,
date(CreationTime) AS LoginDate,
COUNT(*) AS TotalLoginAttempts,
SUM(CASE WHEN Operation = 'UserLoggedIn' THEN 1 ELSE 0 END) AS SuccessfulLogins,
SUM(CASE WHEN Operation = 'UserLoginFailed' THEN 1 ELSE 0 END) AS FailedLogins
FROM
events
where
Operation = 'UserLoggedIn' OR Operation = 'UserLoginFailed'
GROUP BY
UserId,
LoginDate
ORDER BY
LoginDate,
UserId;
'''
User_operations_query = '''
SELECT
UserId,
COUNT(DISTINCT Operation) AS OperationCount,
GROUP_CONCAT(Operation, ', ') AS UniqueOperations
FROM
(SELECT DISTINCT UserId, Operation FROM events)
GROUP BY
UserId
ORDER BY
OperationCount DESC;
'''
user_operation_by_day_query = '''
SELECT
UserId,
DATE(CreationTime) AS OperationDate,
COUNT(DISTINCT Operation) AS OperationCount,
GROUP_CONCAT( Operation, ', ') AS UniqueOperations
FROM
events
GROUP BY
UserId,
OperationDate
ORDER BY
OperationCount DESC
'''
def convert_csv(input_file,temp):
with open(input_file, 'r', encoding='utf-8') as csv_file:
# Create a CSV reader
reader = csv.DictReader(csv_file)
json_file = 'audit_data.json'
json_file=os.path.join(temp, json_file)
with open(json_file, 'w', encoding='utf-8') as jsonl_file:
# Extract and write the AuditData column to a file as JSON Lines
for row in reader:
# Extract the AuditData which is already a JSON formatted string
json_data = json.loads(row['AuditData'])
# Convert the JSON object back to a string to store in the file
json_string = json.dumps(json_data)
# Write the JSON string to the file with a newline
jsonl_file.write(json_string + '\n')
return json_file
def flatten_json_file(input_file, timezone, chunk_size=10000):
# Read the JSON file in chunks
chunks = []
with open(input_file, 'r') as file:
lines = file.readlines()
for i in range(0, len(lines), chunk_size):
chunk = [json.loads(line) for line in lines[i:i + chunk_size]]
# Convert the CreationTime to the desired timezone
for record in chunk:
if 'CreationTime' in record:
# Parse the CreationTime
creation_time = parser.parse(record['CreationTime'])
# Check if the datetime object is timezone aware
if creation_time.tzinfo is None:
# Assume the original time is in UTC if no timezone info is present
creation_time = creation_time.replace(tzinfo=tz.tzutc())
# Convert the CreationTime to the desired timezone
record['CreationTime'] = creation_time.astimezone(timezone).isoformat()
chunks.append(pd.json_normalize(chunk))
# Concatenate all chunks into a single DataFrame
flattened_records = pd.concat(chunks, ignore_index=True)
return flattened_records
def create_sqlite_db_from_dataframe(dataframe, db_name):
conn = sqlite3.connect(db_name)
# Convert all columns to string
dataframe = dataframe.astype(str)
# Write the DataFrame to SQLite, treating all fields as text
dataframe.to_sql('events', conn, if_exists='replace', index=False,
dtype={col_name: 'TEXT' for col_name in dataframe.columns})
conn.close()
def read_detection_rules(rule_file):
with open(rule_file, 'r') as file:
rules = json.load(file)
return rules
def apply_detection_logic_sqlite(db_name, rules):
conn = sqlite3.connect(db_name)
all_detected_events = []
for rule in rules:
rule_name = rule['name']
severity = rule['severity']
query = rule['query']
detected_events = pd.read_sql_query(query, conn)
detected_events['RuleName'] = rule_name
detected_events['Severity'] = severity
all_detected_events.append(detected_events)
conn.close()
if all_detected_events:
result = pd.concat(all_detected_events, ignore_index=True)
else:
result = pd.DataFrame()
return result
def download_geolite_db(geolite_db_path):
url = "https://git.io/GeoLite2-Country.mmdb"
print(f"Downloading GeoLite2 database from {url}...")
response = requests.get(url)
response.raise_for_status() # Check if the download was successful
with open(geolite_db_path, 'wb') as file:
file.write(response.content)
print(f"GeoLite2 database downloaded and saved to {geolite_db_path}")
def get_country_from_ip(ip, reader):
try:
response = reader.country(ip)
return response.country.name
except Exception as e:
#print(f"Could not resolve IP {ip}: {e}")
return 'Unknown'
def analyzeoff365(auditfile, rule_file, output, timezone, include_flattened_data=False,
geolite_db_path='GeoLite2-Country.mmdb'):
start_time = time.time()
temp_dir = ".temp"
if output is None or output == "":
output = os.path.splitext(auditfile)[0]
try:
# Create necessary directories
os.makedirs(output, exist_ok=True)
os.makedirs(temp_dir, exist_ok=True)
# Check if the GeoLite2 database exists, and download it if not
if not os.path.exists(geolite_db_path):
download_geolite_db(geolite_db_path)
# Convert CSV to JSON (assuming convert_csv is a valid function that you have)
json_file = convert_csv(auditfile, temp_dir)
# Input and output file paths
input_file = json_file
db_name = os.path.join(temp_dir, 'audit_data.db')
if rule_file is None:
rule_file = 'O365_detection_rules.json'
output_file = f"{output}_o365_report.xlsx"
# Measure the start time
# Flatten the JSON file
flattened_df = flatten_json_file(input_file, timezone)
# Create SQLite database from the flattened DataFrame
create_sqlite_db_from_dataframe(flattened_df, db_name)
# Open the GeoLite2 database
with geoip2.database.Reader(geolite_db_path) as reader:
# Resolve ClientIP to country names
if 'ClientIP' in flattened_df.columns:
flattened_df['Country'] = flattened_df['ClientIP'].apply(lambda ip: get_country_from_ip(ip, reader))
# Read detection rules
rules = read_detection_rules(rule_file)
# Apply detection logic using SQLite
detected_events = apply_detection_logic_sqlite(db_name, rules)
# Reorder columns to make RuleName the first column
if not detected_events.empty:
columns = ['RuleName', 'Severity'] + [col for col in detected_events.columns if
col not in ['RuleName', 'Severity']]
detected_events = detected_events[columns]
# Perform the brute-force detection query
conn = sqlite3.connect(db_name)
try:
user_login_tracker_df = pd.read_sql_query(user_logon_query, conn)
password_spray_df = pd.read_sql_query(password_spray_query, conn)
user_operations_df = pd.read_sql_query(User_operations_query, conn)
user_operation_by_day_df = pd.read_sql_query(user_operation_by_day_query, conn)
finally:
conn.close()
# Create a new workbook with the detection results
with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:
if include_flattened_data:
# Split the flattened data into multiple sheets if needed
max_rows_per_sheet = 65000
num_sheets = len(flattened_df) // max_rows_per_sheet + 1
for i in range(num_sheets):
start_row = i * max_rows_per_sheet
end_row = (i + 1) * max_rows_per_sheet
sheet_name = f'Flattened Data {i + 1}'
flattened_df.iloc[start_row:end_row].to_excel(writer, sheet_name=sheet_name, index=False)
# Write statistics for various fields
detected_events.to_excel(writer, sheet_name='Detection Results', index=False)
user_login_tracker_df.to_excel(writer, sheet_name='User Login Tracker', index=False)
password_spray_df.to_excel(writer, sheet_name='Password Spray Attacks', index=False)
user_operations_df.to_excel(writer, sheet_name='User Operations', index=False)
user_operation_by_day_df.to_excel(writer, sheet_name='User Operations by Day', index=False)
flattened_df['Operation'].value_counts().to_frame().to_excel(writer, sheet_name='Operation Stats')
flattened_df['ClientIP'].value_counts().to_frame().to_excel(writer, sheet_name='ClientIP Stats')
flattened_df['Country'].value_counts().to_frame().to_excel(writer, sheet_name='Country Stats')
flattened_df['UserAgent'].value_counts().to_frame().to_excel(writer, sheet_name='UserAgent Stats')
flattened_df['UserId'].value_counts().to_frame().to_excel(writer, sheet_name='UserId Stats')
flattened_df['AuthenticationType'].value_counts().to_frame().to_excel(writer,
sheet_name='AuthenticationType Stats')
# Measure the end time
end_time = time.time()
print(f"Office365 analysis finished in time: {end_time - start_time:.2f} seconds")
except Exception as e:
print(f"An error occurred during the analysis: {e}")
finally:
#Clean up the temporary directory
if os.path.exists(temp_dir):
for file in Path(temp_dir).glob('*'):
file.unlink() # Delete the file
os.rmdir(temp_dir) # Remove the directory
# Write the User Login Tracker results to a new sheet
# Measure the end time
end_time = time.time()
# Calculate and print the running time
running_time = end_time - start_time
print(f"Office365 hunter finished in time: {running_time:.2f} seconds")

File diff suppressed because one or more lines are too long

@ -1,722 +0,0 @@
title: Combination of configs
order: 15
# Taken from https://github.com/SigmaHQ/legacy-sigmatools/blob/master/tools/config/
logsources:
ps_module:
category: ps_module
product: windows
conditions:
EventID: 4103
rewrite:
product: windows
service: powershell
ps_script:
category: ps_script
product: windows
conditions:
EventID: 4104
rewrite:
product: windows
service: powershell
# for the "classic" channel
ps_classic_start:
category: ps_classic_start
product: windows
conditions:
EventID: 400
rewrite:
product: windows
service: powershell-classic
ps_classic_provider_start:
category: ps_classic_provider_start
product: windows
conditions:
EventID: 600
rewrite:
product: windows
service: powershell-classic
ps_classic_script:
category: ps_classic_script
product: windows
conditions:
EventID: 800
rewrite:
product: windows
service: powershell-classic
process_creation:
category: process_creation
product: windows
conditions:
EventID: 4688
rewrite:
product: windows
service: security
registry_event:
category: registry_event
product: windows
conditions:
EventID: 4657
OperationType:
- 'New registry value created'
- 'Existing registry value modified'
rewrite:
product: windows
service: security
registry_event_set:
category: registry_set
product: windows
conditions:
EventID: 4657
OperationType:
- 'Existing registry value modified'
rewrite:
product: windows
service: security
registry_event_add:
category: registry_add
product: windows
conditions:
EventID: 4657
OperationType:
- 'New registry value created'
rewrite:
product: windows
service: security
ps_module:
category: ps_module
product: windows
conditions:
EventID: 4103
rewrite:
product: windows
service: powershell
ps_script:
category: ps_script
product: windows
conditions:
EventID: 4104
rewrite:
product: windows
service: powershell
# for the "classic" channel
ps_classic_start:
category: ps_classic_start
product: windows
conditions:
EventID: 400
rewrite:
product: windows
service: powershell-classic
ps_classic_provider_start:
category: ps_classic_provider_start
product: windows
conditions:
EventID: 600
rewrite:
product: windows
service: powershell-classic
ps_classic_script:
category: ps_classic_script
product: windows
conditions:
EventID: 800
rewrite:
product: windows
service: powershell-classic
windows-application:
product: windows
service: application
conditions:
Channel: Application
windows-security:
product: windows
service: security
conditions:
Channel: Security
windows-system:
product: windows
service: system
conditions:
Channel: System
windows-sysmon:
product: windows
service: sysmon
conditions:
Channel: 'Microsoft-Windows-Sysmon/Operational'
windows-powershell:
product: windows
service: powershell
conditions:
Channel:
- 'Microsoft-Windows-PowerShell/Operational'
- 'PowerShellCore/Operational'
windows-classicpowershell:
product: windows
service: powershell-classic
conditions:
Channel: 'Windows PowerShell'
windows-dns-server:
product: windows
service: dns-server
conditions:
Channel: 'DNS Server'
windows-driver-framework:
product: windows
service: driver-framework
conditions:
Channel: 'Microsoft-Windows-DriverFrameworks-UserMode/Operational'
windows-dhcp:
product: windows
service: dhcp
conditions:
Channel: 'Microsoft-Windows-DHCP-Server/Operational'
windows-ntlm:
product: windows
service: ntlm
conditions:
Channel: 'Microsoft-Windows-NTLM/Operational'
windows-defender:
product: windows
service: windefend
conditions:
Channel: 'Microsoft-Windows-Windows Defender/Operational'
windows-printservice-admin:
product: windows
service: printservice-admin
conditions:
Channel: 'Microsoft-Windows-PrintService/Admin'
windows-printservice-operational:
product: windows
service: printservice-operational
conditions:
Channel: 'Microsoft-Windows-PrintService/Operational'
windows-terminalservices-localsessionmanager-operational:
product: windows
service: terminalservices-localsessionmanager
conditions:
Channel: 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
windows-smbclient-security:
product: windows
service: smbclient-security
conditions:
Channel: 'Microsoft-Windows-SmbClient/Security'
windows-applocker:
product: windows
service: applocker
conditions:
Channel:
- 'Microsoft-Windows-AppLocker/MSI and Script'
- 'Microsoft-Windows-AppLocker/EXE and DLL'
- 'Microsoft-Windows-AppLocker/Packaged app-Deployment'
- 'Microsoft-Windows-AppLocker/Packaged app-Execution'
windows-msexchange-management:
product: windows
service: msexchange-management
conditions:
Channel: 'MSExchange Management'
windows-servicebus-client:
product: windows
service: microsoft-servicebus-client
conditions:
Channel: 'Microsoft-ServiceBus-Client'
windows-ladp-client-debug:
product: windows
service: ldap_debug
conditions:
Channel: 'Microsoft-Windows-LDAP-Client/Debug'
windows-taskscheduler-operational:
product: windows
service: taskscheduler
conditions:
Channel: 'Microsoft-Windows-TaskScheduler/Operational'
windows-wmi-activity-Operational:
product: windows
service: wmi
conditions:
Channel: 'Microsoft-Windows-WMI-Activity/Operational'
windows-codeintegrity-operational:
product: windows
service: codeintegrity-operational
conditions:
Channel: 'Microsoft-Windows-CodeIntegrity/Operational'
windows-firewall-advanced-security:
product: windows
service: firewall-as
conditions:
Channel: 'Microsoft-Windows-Windows Firewall With Advanced Security/Firewall'
windows-bits-client:
product: windows
service: bits-client
conditions:
Channel: 'Microsoft-Windows-Bits-Client/Operational'
windows-diagnosis-scripted:
product: windows
service: diagnosis-scripted
conditions:
Channel: 'Microsoft-Windows-Diagnosis-Scripted/Operational'
windows-shell-core:
product: windows
service: shell-core
conditions:
Channel: 'Microsoft-Windows-Shell-Core/Operational'
windows-security-mitigations:
product: windows
service: security-mitigations
conditions:
Channel: 'Microsoft-Windows-Security-Mitigations'
windows-openssh:
product: windows
service: openssh
conditions:
Channel: 'OpenSSH/Operational'
windows-ldap-debug:
product: windows
service: ldap_debug
conditions:
Channel: 'Microsoft-Windows-LDAP-Client/Debug'
windows-vhdmp-operational:
product: windows
service: vhdmp
conditions:
Channel: 'Microsoft-Windows-VHDMP/Operational'
windows-appxdeployment-server:
product: windows
service: appxdeployment-server
conditions:
Channel: 'Microsoft-Windows-AppXDeploymentServer/Operational'
windows-lsa-server:
product: windows
service: lsa-server
conditions:
Channel: 'Microsoft-Windows-LSA/Operational'
windows-appxpackaging-om:
product: windows
service: appxpackaging-om
conditions:
Channel: 'Microsoft-Windows-AppxPackaging/Operational'
windows-dns-client:
product: windows
service: dns-client
conditions:
Channel: 'Microsoft-Windows-DNS Client Events/Operational'
windows-appmodel-runtime:
product: windows
service: appmodel-runtime
conditions:
Channel: 'Microsoft-Windows-AppModel-Runtime/Admin'
windows-application:
product: windows
service: application
conditions:
Channel: Application
windows-security:
product: windows
service: security
conditions:
Channel: Security
windows-system:
product: windows
service: system
conditions:
Channel: System
windows-sysmon:
product: windows
service: sysmon
conditions:
Channel: 'Microsoft-Windows-Sysmon/Operational'
windows-powershell:
product: windows
service: powershell
conditions:
Channel:
- 'Microsoft-Windows-PowerShell/Operational'
- 'PowerShellCore/Operational'
windows-classicpowershell:
product: windows
service: powershell-classic
conditions:
Channel: 'Windows PowerShell'
windows-dns-server:
product: windows
service: dns-server
conditions:
Channel: 'DNS Server'
windows-driver-framework:
product: windows
service: driver-framework
conditions:
Provider_Name: 'Microsoft-Windows-DriverFrameworks-UserMode/Operational'
windows-dhcp:
product: windows
service: dhcp
conditions:
Provider_Name: 'Microsoft-Windows-DHCP-Server/Operational'
windows-ntlm:
product: windows
service: ntlm
conditions:
Provider_Name: 'Microsoft-Windows-NTLM/Operational'
windows-defender:
product: windows
service: windefend
conditions:
Channel: 'Microsoft-Windows-Windows Defender/Operational'
windows-printservice-admin:
product: windows
service: printservice-admin
conditions:
Channel: 'Microsoft-Windows-PrintService/Admin'
windows-printservice-operational:
product: windows
service: printservice-operational
conditions:
Channel: 'Microsoft-Windows-PrintService/Operational'
windows-terminalservices-localsessionmanager-operational:
product: windows
service: terminalservices-localsessionmanager
conditions:
Channel: 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
windows-codeintegrity-operational:
product: windows
service: codeintegrity-operational
conditions:
Channel: 'Microsoft-Windows-CodeIntegrity/Operational'
windows-smbclient-security:
product: windows
service: smbclient-security
conditions:
Channel: 'Microsoft-Windows-SmbClient/Security'
windows-applocker:
product: windows
service: applocker
conditions:
Channel:
- 'Microsoft-Windows-AppLocker/MSI and Script'
- 'Microsoft-Windows-AppLocker/EXE and DLL'
- 'Microsoft-Windows-AppLocker/Packaged app-Deployment'
- 'Microsoft-Windows-AppLocker/Packaged app-Execution'
windows-msexchange-management:
product: windows
service: msexchange-management
conditions:
Channel: 'MSExchange Management'
microsoft-servicebus-client:
product: windows
service: microsoft-servicebus-client
conditions:
Channel: 'Microsoft-ServiceBus-Client'
windows-firewall-advanced-security:
product: windows
service: firewall-as
conditions:
Channel: 'Microsoft-Windows-Windows Firewall With Advanced Security/Firewall'
windows-bits-client:
product: windows
service: bits-client
conditions:
Channel: 'Microsoft-Windows-Bits-Client/Operational'
windows-vhdmp-Operational:
product: windows
service: vhdmp
conditions:
Channel: 'Microsoft-Windows-VHDMP/Operational'
windows-appxdeployment-server:
product: windows
service: appxdeployment-server
conditions:
Channel: 'Microsoft-Windows-AppXDeploymentServer/Operational'
windows-lsa-server:
product: windows
service: lsa-server
conditions:
Channel: 'Microsoft-Windows-LSA/Operational'
windows-appxpackaging-om:
product: windows
service: appxpackaging-om
conditions:
Channel: 'Microsoft-Windows-AppxPackaging/Operational'
windows-dns-client:
product: windows
service: dns-client
conditions:
Channel: 'Microsoft-Windows-DNS Client Events/Operational'
windows-appmodel-runtime:
product: windows
service: appmodel-runtime
conditions:
Channel: 'Microsoft-Windows-AppModel-Runtime/Admin'
process_creation:
category: process_creation
product: windows
conditions:
EventID: 1
rewrite:
product: windows
service: sysmon
process_creation_linux:
category: process_creation
product: linux
conditions:
EventID: 1
rewrite:
product: linux
service: sysmon
file_change:
category: file_change
product: windows
conditions:
EventID: 2
rewrite:
product: windows
service: sysmon
network_connection:
category: network_connection
product: windows
conditions:
EventID: 3
rewrite:
product: windows
service: sysmon
network_connection_linux:
category: network_connection
product: linux
conditions:
EventID: 3
rewrite:
product: linux
service: sysmon
sysmon_status:
category: sysmon_status
product: windows
conditions:
EventID:
- 4
- 16
rewrite:
product: windows
service: sysmon
sysmon_status_linux:
category: sysmon_status
product: linux
conditions:
EventID: 16
rewrite:
product: linux
service: sysmon
process_terminated:
category: process_termination
product: windows
conditions:
EventID: 5
rewrite:
product: windows
service: sysmon
process_terminated_linux:
category: process_termination
product: linux
conditions:
EventID: 5
rewrite:
product: linux
service: sysmon
driver_loaded:
category: driver_load
product: windows
conditions:
EventID: 6
rewrite:
product: windows
service: sysmon
image_loaded:
category: image_load
product: windows
conditions:
EventID: 7
rewrite:
product: windows
service: sysmon
create_remote_thread:
category: create_remote_thread
product: windows
conditions:
EventID: 8
rewrite:
product: windows
service: sysmon
raw_access_thread:
category: raw_access_thread
product: windows
conditions:
EventID: 9
rewrite:
product: windows
service: sysmon
process_access:
category: process_access
product: windows
conditions:
EventID: 10
rewrite:
product: windows
service: sysmon
raw_access_read_linux:
category: raw_access_read
product: linux
conditions:
EventID: 9
rewrite:
product: linux
service: sysmon
file_creation:
category: file_event
product: windows
conditions:
EventID: 11
rewrite:
product: windows
service: sysmon
file_creation_linux:
category: file_event
product: linux
conditions:
EventID: 11
rewrite:
product: linux
service: sysmon
registry_add:
category: registry_add
product: windows
conditions:
EventID: 12
rewrite:
product: windows
service: sysmon
registry_delete:
category: registry_delete
product: windows
conditions:
EventID: 12
rewrite:
product: windows
service: sysmon
registry_set:
category: registry_set
product: windows
conditions:
EventID: 13
rewrite:
product: windows
service: sysmon
registry_rename:
category: registry_rename
product: windows
conditions:
EventID: 14
rewrite:
product: windows
service: sysmon
registry_event:
category: registry_event
product: windows
conditions:
EventID:
- 12
- 13
- 14
rewrite:
product: windows
service: sysmon
create_stream_hash:
category: create_stream_hash
product: windows
conditions:
EventID: 15
rewrite:
product: windows
service: sysmon
pipe_created:
category: pipe_created
product: windows
conditions:
EventID:
- 17
- 18
rewrite:
product: windows
service: sysmon
wmi_event:
category: wmi_event
product: windows
conditions:
EventID:
- 19
- 20
- 21
rewrite:
product: windows
service: sysmon
dns_query:
category: dns_query
product: windows
conditions:
EventID: 22
rewrite:
product: windows
service: sysmon
file_delete:
category: file_delete
product: windows
conditions:
EventID:
- 23
- 26
rewrite:
product: windows
service: sysmon
file_delete_linux:
category: file_delete
product: linux
conditions:
EventID: 23
rewrite:
product: linux
service: sysmon
clipboard_capture:
category: clipboard_capture
product: windows
conditions:
EventID: 24
rewrite:
product: windows
service: sysmon
process_tampering:
category: process_tampering
product: windows
conditions:
EventID: 25
rewrite:
product: windows
service: sysmon
file_block:
category: file_block
product: windows
conditions:
EventID: 27
rewrite:
product: windows
service: sysmon
sysmon_error:
category: sysmon_error
product: windows
conditions:
EventID: 255
rewrite:
product: windows
service: sysmon
fieldmappings:
Image: NewProcessName
ParentImage: ParentProcessName
Details: NewValue
#CommandLine: ProcessCommandLine # No need to map, as real name of ProcessCommandLine is already CommandLine
LogonId: SubjectLogonId

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

@ -1,11 +0,0 @@
evtx
netaddr
numpy
pandas
python-dateutil
pytz
six
XlsxWriter
flatten_json
geoip2
requests

File diff suppressed because one or more lines are too long

@ -1,101 +0,0 @@
try{
New-Item -ItemType "directory" -Path "wineventlog"
}
catch
{
echo "can't create a new directory"
}
try{
get-eventlog -log Security | export-csv wineventlog/Security.csv
}
catch
{
echo "Can't retrieve Security Logs"
}
try
{
Get-WinEvent -LogName System | export-csv wineventlog/System.csv
}
catch
{
echo "Can't retrieve System Logs"
}
try{
Get-WinEvent -LogName Application | export-csv wineventlog/Application.csv
}
catch
{
echo "Can't retrieve Application Logs"
}
try{
Get-WinEvent -LogName "Windows PowerShell" | export-csv wineventlog/Windows_PowerShell.csv
}
catch
{
echo "Can't retrieve Windows PowerShell Logs"
}
try{
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | export-csv wineventlog/LocalSessionManager.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-TerminalServices-LocalSessionManager/Operational Logs"
}
try{
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" | export-csv wineventlog/Windows_Defender.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-Windows Defender/Operational Logs"
}
try{
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational | export-csv wineventlog/TaskScheduler.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-TaskScheduler/Operational Logs"
}
try{
Get-WinEvent -LogName Microsoft-Windows-WinRM/Operational | export-csv wineventlog/WinRM.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-WinRM/Operational Logs"
}
try{
Get-WinEvent -LogName Microsoft-Windows-Sysmon/Operational | export-csv wineventlog/Sysmon.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-Sysmon/Operational Logs"
}
try{
Get-WinEvent -LogName Microsoft-Windows-PowerShell/Operational | export-csv wineventlog/Powershell_Operational.csv
}
catch
{
echo "Can't retrieve Microsoft-Windows-PowerShell/Operational Logs"
}
try
{
Compress-Archive -Path wineventlog -DestinationPath ./logs.zip
}
catch
{
echo "couldn't compress the the log folder "
}

@ -1,101 +0,0 @@
try{
New-Item -ItemType "directory" -Path "wineventlog"
}
catch
{
echo "can't create a new directory"
}
try{
wevtutil epl Security wineventlog/Security.evtx
}
catch
{
echo "Can't retrieve Security Logs"
}
try
{
wevtutil epl System wineventlog/System.evtx
}
catch
{
echo "Can't retrieve System Logs"
}
try{
wevtutil epl Application wineventlog/Application.evtx
}
catch
{
echo "Can't retrieve Application Logs"
}
try{
wevtutil epl "Windows PowerShell" wineventlog/Windows_PowerShell.evtx
}
catch
{
echo "Can't retrieve Windows PowerShell Logs"
}
try{
wevtutil epl "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" wineventlog/LocalSessionManager.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-TerminalServices-LocalSessionManager/Operational Logs"
}
try{
wevtutil epl "Microsoft-Windows-Windows Defender/Operational" wineventlog/Windows_Defender.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-Windows Defender/Operational Logs"
}
try{
wevtutil epl Microsoft-Windows-TaskScheduler/Operational wineventlog/TaskScheduler.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-TaskScheduler/Operational Logs"
}
try{
wevtutil epl Microsoft-Windows-WinRM/Operational wineventlog/WinRM.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-WinRM/Operational Logs"
}
try{
wevtutil epl Microsoft-Windows-Sysmon/Operational wineventlog/Sysmon.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-Sysmon/Operational Logs"
}
try{
wevtutil epl Microsoft-Windows-PowerShell/Operational wineventlog/Powershell_Operational.evtx
}
catch
{
echo "Can't retrieve Microsoft-Windows-PowerShell/Operational Logs"
}
try
{
Compress-Archive -Path wineventlog -DestinationPath ./logs.zip
}
catch
{
echo "couldn't compress the the log folder "
}
Loading…
Cancel
Save