Compare commits

..

No commits in common. 'main' and 'NineLamp' have entirely different histories.

@ -1,24 +1,15 @@
#!/bin/bash
# 检查脚本是否只有一个参数输入
if [ "$#" -ne 1 ]; then
echo "Please enter rules path as argument "
exit 1
fi
# 输出正在克隆Sigma转换工具的信息
echo "Getting Sigma Converter Toot"
# 使用git克隆SigmaHQ的legacy-sigmatools仓库到当前目录
git clone https://github.com/SigmaHQ/legacy-sigmatools.git
# 输出正在转换sigma规则的信息
echo "Converting sigma rules "
# 执行Sigma转换工具将sigma规则文件转换为json格式
# --recurse: 递归处理指定目录下的所有规则文件
# --target sqlite: 指定转换的目标格式为sqlite
# --backend-option table=Events: 指定输出的表名为Events
# -d $1: 指定sigma规则文件的目录为脚本的第一个参数
# -c lib/config/sigma-converter-rules-config.yml: 指定配置文件路径
# -o rules.json: 指定输出文件名为rules.json
# --output-fields: 指定输出的字段内容
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,23 +1,11 @@
#!/bin/bash
# 输出转换完成的信息,包括生成的文件名
echo "Getting Sigma Converter Toot"
# 使用git克隆SigmaHQ的legacy-sigmatools仓库到当前目录
git clone https://github.com/SigmaHQ/legacy-sigmatools.git
# 使用git克隆SigmaHQ的legacy-sigmatools仓库到当前目录
echo "Getting Sigma Rules"
# 使用git克隆SigmaHQ的legacy-sigmatools仓库到当前目录
git clone https://github.com/SigmaHQ/sigma.git
# 输出正在转换sigma规则的信息
echo "Converting sigma rules "
# 执行Sigma转换工具将sigma规则文件转换为json格式
# --recurse: 递归处理指定目录下的所有规则文件
# --target sqlite: 指定转换的目标格式为sqlite
# --backend-option table=Events: 指定输出的表名为Events
# -d sigma/rules/windows/: 指定sigma规则文件的目录为sigma仓库中的windows规则目录
# -c lib/config/sigma-converter-rules-config.yml: 指定配置文件路径
# -o rules.json: 指定输出文件名为rules.json
# --output-fields: 指定输出的字段内容
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,6 +1,4 @@
{
"description": "此 JSON 文件包含与 O365 安全检测相关的规则,每条规则包括名称、严重性等级和查询语句。",
"rules": [
[
{
"name": "Suspicious User Agent",
"severity": "High",
@ -96,5 +94,6 @@
"severity": "High",
"query": "SELECT * FROM events WHERE ( Operation LIKE '%Disable Strong Authentication.%' ) "
}
]
}

@ -8,134 +8,87 @@ minlength=1000
account_op={}
PasswordSpray={}
# 定义可疑的可执行文件列表
Suspicious_executables=['pl.exe','nc.exe','nmap.exe','psexec.exe','plink.exe','mimikatz','procdump.exe',' dcom.exe',' Inveigh.exe',' LockLess.exe',' Logger.exe',' PBind.exe',' PS.exe',' Rubeus.exe',' RunasCs.exe',' RunAs.exe',' SafetyDump.exe',' SafetyKatz.exe',' Seatbelt.exe',' SExec.exe',' SharpApplocker.exe',' SharpChrome.exe',' SharpCOM.exe',' SharpDPAPI.exe',' SharpDump.exe',' SharpEdge.exe',' SharpEDRChecker.exe',' SharPersist.exe',' SharpHound.exe',' SharpLogger.exe',' SharpPrinter.exe',' SharpRoast.exe',' SharpSC.exe',' SharpSniper.exe',' SharpSocks.exe',' SharpSSDP.exe',' SharpTask.exe',' SharpUp.exe',' SharpView.exe',' SharpWeb.exe',' SharpWMI.exe',' Shhmon.exe',' SweetPotato.exe',' Watson.exe',' WExec.exe','7zip.exe']
# 定义可疑的 PowerShell 命令列表
Suspicious_powershell_commands=['Get-WMIObject','Get-GPPPassword','Get-Keystrokes','Get-TimedScreenshot','Get-VaultCredential','Get-ServiceUnquoted','Get-ServiceEXEPerms','Get-ServicePerms','Get-RegAlwaysInstallElevated','Get-RegAutoLogon','Get-UnattendedInstallFiles','Get-Webconfig','Get-ApplicationHost','Get-PassHashes','Get-LsaSecret','Get-Information','Get-PSADForestInfo','Get-KerberosPolicy','Get-PSADForestKRBTGTInfo','Get-PSADForestInfo','Get-KerberosPolicy','Invoke-Command','Invoke-Expression','iex','Invoke-Shellcode','Invoke--Shellcode','Invoke-ShellcodeMSIL','Invoke-MimikatzWDigestDowngrade','Invoke-NinjaCopy','Invoke-CredentialInjection','Invoke-TokenManipulation','Invoke-CallbackIEX','Invoke-PSInject','Invoke-DllEncode','Invoke-ServiceUserAdd','Invoke-ServiceCMD','Invoke-ServiceStart','Invoke-ServiceStop','Invoke-ServiceEnable','Invoke-ServiceDisable','Invoke-FindDLLHijack','Invoke-FindPathHijack','Invoke-AllChecks','Invoke-MassCommand','Invoke-MassMimikatz','Invoke-MassSearch','Invoke-MassTemplate','Invoke-MassTokens','Invoke-ADSBackdoor','Invoke-CredentialsPhish','Invoke-BruteForce','Invoke-PowerShellIcmp','Invoke-PowerShellUdp','Invoke-PsGcatAgent','Invoke-PoshRatHttps','Invoke-PowerShellTcp','Invoke-PoshRatHttp','Invoke-PowerShellWmi','Invoke-PSGcat','Invoke-Encode','Invoke-Decode','Invoke-CreateCertificate','Invoke-NetworkRelay','EncodedCommand','New-ElevatedPersistenceOption','wsman','Enter-PSSession','DownloadString','DownloadFile','Out-Word','Out-Excel','Out-Java','Out-Shortcut','Out-CHM','Out-HTA','Out-Minidump','HTTP-Backdoor','Find-AVSignature','DllInjection','ReflectivePEInjection','Base64','System.Reflection','System.Management','Restore-ServiceEXE','Add-ScrnSaveBackdoor','Gupt-Backdoor','Execute-OnTime','DNS_TXT_Pwnage','Write-UserAddServiceBinary','Write-CMDServiceBinary','Write-UserAddMSI','Write-ServiceEXE','Write-ServiceEXECMD','Enable-DuplicateToken','Remove-Update','Execute-DNSTXT-Code','Download-Execute-PS','Execute-Command-MSSQL','Download_Execute','Copy-VSS','Check-VM','Create-MultipleSessions','Run-EXEonRemote','Port-Scan','Remove-PoshRat','TexttoEXE','Base64ToString','StringtoBase64','Do-Exfiltration','Parse_Keys','Add-Exfiltration','Add-Persistence','Remove-Persistence','Find-PSServiceAccounts','Discover-PSMSSQLServers','Discover-PSMSExchangeServers','Discover-PSInterestingServices','Discover-PSMSExchangeServers','Discover-PSInterestingServices','Mimikatz','powercat','powersploit','PowershellEmpire','Payload','GetProcAddress','ICM','.invoke',' -e ','hidden','-w hidden']
# 定义 PowerShell 参数列表
Suspicious_powershell_Arguments=["-EncodedCommand","-enc","-w hidden","[Convert]::FromBase64String","iex(","New-Object","Net.WebClient","-windowstyle hidden","DownloadFile","DownloadString","Invoke-Expression","Net.WebClient","-Exec bypass" ,"-ExecutionPolicy bypass"]
# 定义终端服务摘要
TerminalServices_Summary=[{'User':[],'Number of Logins':[]}]
# 定义安全认证摘要
Security_Authentication_Summary=[{'User':[],'Number of Failed Logins':[],'Number of Successful Logins':[]}]
# 定义执行进程摘要
Executed_Process_Summary=[{'Process Name':[],'Number of Execution':[]}]
# 定义关键服务列表
critical_services=["Software Protection","Network List Service","Network Location Awareness","Windows Event Log"]
# 定义 Sysmon 事件结构
Sysmon_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
# 定义 WinRM 事件结构
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 事件结构
Powershell_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
# 定义 PowerShell 操作事件结构
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 事件结构
Windows_Defender_events=[{'Date and Time':[],'timestamp':[],'Detection Rule':[],'Severity':[],'Detection Domain':[],'Event Description':[],'Event ID':[],'Original Event Log':[]}]
# 定义 Timesketch 事件结构
Timesketch_events=[{'message':[],'timestamp':[],'datetime':[],'timestamp_desc':[],'Event Description':[],'Severity':[],'Detection Domain':[],'Event ID':[],'Original Event Log':[]}]
#=======================
#Regex for security logs
# 定义安全日志的正则表达式
Logon_Type_rex = re.compile('Logon Type:\t{1,15}(\d{1,4})', re.IGNORECASE)
# 定义账户名称的正则表达式
#Account_Name_rex = re.compile('Account Name:\t{1,15}(.*)', re.IGNORECASE)
Account_Name_rex = re.compile('Account Name:(.*)', re.IGNORECASE)
# 定义安全 ID 的正则表达式
Security_ID_rex = re.compile('Security ID:\t{1,15}(.*)', re.IGNORECASE)
# 定义账户域的正则表达式
Account_Domain_rex = re.compile('Account Domain:\t{1,15}(.*)', re.IGNORECASE)
# 定义工作站名称的正则表达式
Workstation_Name_rex = re.compile('Workstation Name:\t{1,15}(.*)', re.IGNORECASE)
# 定义源网络地址的正则表达式
Source_Network_Address_rex = re.compile('Source Network Address:\t{1,15}(.*)', re.IGNORECASE)
# 定义登录进程的正则表达式
Logon_Process_rex = re.compile('Logon Process:\t{1,15}(.*)', re.IGNORECASE)
# 定义密钥长度的正则表达式
Key_Length_rex = re.compile('Key Length:\t{1,15}(\d{1,4})', re.IGNORECASE)
# 定义进程命令行的正则表达式
Process_Command_Line_rex=re.compile('Process Command Line:\t{1,15}(.*)', re.IGNORECASE)
# 定义组名称的正则表达式
Group_Name_rex=re.compile('Group Name:\t{1,15}(.*)', re.IGNORECASE)
# 定义任务名称的正则表达式
Task_Name_rex=re.compile('Task Name: \t{1,10}(.*)', re.IGNORECASE)
# 定义任务命令的正则表达式
Task_Command_rex=re.compile('<Command>(.*)</Command>', re.IGNORECASE)
# 定义任务参数的正则表达式
Task_args_rex=re.compile('<Arguments>(.*)</Arguments>', re.IGNORECASE)
# 定义进程名称的正则表达式
Process_Name_sec_rex = re.compile('Process Name:\t{1,15}(.*)', re.IGNORECASE)
# 定义类别的正则表达式
Category_sec_rex= re.compile('Category:\t{1,15}(.*)', re.IGNORECASE)
# 定义子类别的正则表达式
Subcategory_rex= re.compile('Subcategory:\t{1,15}(.*)', re.IGNORECASE)
# 定义更改的正则表达式
Changes_rex= re.compile('Changes:\t{1,15}(.*)', re.IGNORECASE)
#=======================
# 定义 Windows Defender 日志的正则表达式
#Regex for windows defender logs
Name_rex = re.compile('\t{1,15}Name: (.*)', re.IGNORECASE)
# 定义严重性级别的正则表达式
Severity_rex = re.compile('\t{1,15}Severity: (.*)', re.IGNORECASE)
# 定义类别的正则表达式
Category_rex = re.compile('\t{1,15}Category: (.*)', re.IGNORECASE)
# 定义路径的正则表达式
Path_rex = re.compile('\t{1,15}Path: (.*)', re.IGNORECASE)
# 定义用户的正则表达式
Defender_User_rex = re.compile('\t{1,15}User: (.*)', re.IGNORECASE)
# 定义进程名称的正则表达式
Process_Name_rex = re.compile('\t{1,15}Process Name: (.*)', re.IGNORECASE)
# 定义操作的正则表达式
Action_rex = re.compile('\t{1,15}Action: (.*)', re.IGNORECASE)
#=======================
# 定义系统日志的正则表达式
#Regex for system logs
Service_Name_rex = re.compile('Service Name: (.*)', re.IGNORECASE)
Service_File_Name_rex = re.compile('Service File Name: (.*)', re.IGNORECASE)
Service_Type_rex = re.compile('Service Type: (.*)', re.IGNORECASE)
@ -144,14 +97,16 @@ Service_and_state_rex = re.compile('The (.*) service entered the (.*) state\.',
StartType_rex = re.compile('The start type of the (.*) service was changed', re.IGNORECASE)
Service_Start_Type_rex = re.compile('Service Start Type: (.*)', re.IGNORECASE)
#=======================
# 定义任务调度程序日志的正则表达式
#Regex for task scheduler logs
task_register_rex = re.compile('User \"(.*)\" registered Task Scheduler task \"(.*)\"', re.IGNORECASE)
task_update_rex = re.compile('User \"(.*)\" updated Task Scheduler task \"(.*)\"', re.IGNORECASE)
task_delete_rex = re.compile('User \"(.*)\" deleted Task Scheduler task \"(.*)\"', re.IGNORECASE)
# =======================
# 定义 PowerShell 操作日志的正则表达式
#======================
#Regex for powershell operational logs
Host_Application_rex = re.compile('Host Application = (.*)')
Command_Name_rex = re.compile('Command Name = (.*)')
Command_Type_rex = re.compile('Command Type = (.*)')
@ -159,27 +114,27 @@ Engine_Version_rex = re.compile('Engine Version = (.*)')
User_rex = re.compile('User = (.*)')
Error_Message_rex = re.compile('Error Message = (.*)')
# =======================
# 定义 PowerShell 日志的正则表达式
#======================
#Regex for powershell logs
HostApplication_rex = re.compile('HostApplication=(.*)')
CommandLine_rex = re.compile('CommandLine=(.*)')
ScriptName_rex = re.compile('ScriptName=(.*)')
EngineVersion_rex = re.compile('EngineVersion=(.*)')
UserId_rex = re.compile('UserId=(.*)')
ErrorMessage_rex = re.compile('ErrorMessage=(.*)')
# =======================
# 定义终端服务本地会话管理器日志的正则表达式
#======================
#TerminalServices Local Session Manager Logs
#Source_Network_Address_Terminal_rex= re.compile('Source Network Address: (.*)')
Source_Network_Address_Terminal_rex= re.compile('Source Network Address: ((\d{1,3}\.){3}\d{1,3})')
User_Terminal_rex=re.compile('User: (.*)')
Session_ID_rex=re.compile('Session ID: (.*)')
# =======================
# 定义 Microsoft-Windows-WinRM 日志的正则表达式
#======================
#Microsoft-Windows-WinRM logs
Connection_rex=re.compile("""The connection string is: (.*)""")
# =======================
# 定义 Sysmon 日志的正则表达式
#User_ID_rex=re.compile("""<Security UserID=\'(?<UserID>.*)\'\/><\/System>""")
#src_device_rex=re.compile("""<Computer>(?<src>.*)<\/Computer>""")
#======================
#Sysmon Logs
Sysmon_CommandLine_rex=re.compile("CommandLine: (.*)")
Sysmon_ProcessGuid_rex=re.compile("ProcessGuid: (.*)")
Sysmon_ProcessId_rex=re.compile("ProcessId: (.*)")
@ -200,9 +155,8 @@ Sysmon_ParentCommandLine_rex = re.compile("ParentCommandLine: (.*)")
Sysmon_CurrentDirectory_rex=re.compile("CurrentDirectory: (.*)")
Sysmon_OriginalFileName_rex=re.compile("OriginalFileName: (.*)")
Sysmon_TargetObject_rex=re.compile("TargetObject: (.*)")
# =======================
# Sysmon 事件 ID 3 的正则表达式
#########
#Sysmon event ID 3
Sysmon_Protocol_rex=re.compile("Protocol: (.*)")
Sysmon_SourceIp_rex=re.compile("SourceIp: (.*)")
Sysmon_SourceHostname_rex=re.compile("SourceHostname: (.*)")
@ -210,9 +164,8 @@ Sysmon_SourcePort_rex = re.compile("SourcePort: (.*)")
Sysmon_DestinationIp_rex=re.compile("DestinationIp: (.*)")
Sysmon_DestinationHostname_rex=re.compile("DestinationHostname: (.*)")
Sysmon_DestinationPort_rex=re.compile("DestinationPort: (.*)")
# =======================
# Sysmon 事件 ID 8 的正则表达式
#########
#Sysmon event ID 8
Sysmon_StartFunction_rex=re.compile("StartFunction: (.*)")
Sysmon_StartModule_rex=re.compile("StartModule: (.*)")
Sysmon_TargetImage_rex=re.compile("TargetImage: (.*)")
@ -236,45 +189,53 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
"""
if open(file_name,"r").read(1000).find("\"InstanceId\",\"TimeGenerated\"")>0:
# 如果包含,使用包含更多字段的字典读取器
list2 = csv.DictReader(csvfile,
fieldnames=('Event ID', "MachineName", "Data", "Index", "Category", "CategoryNumber",
"EntryType", "Details", "Source", "ReplacementStrings", "InstanceId",
'Date and Time', "TimeWritten", "UserName", "Site", "Container"))
else:
# 如果不包含,使用较少字段的字典读取器
list2 = csv.DictReader(csvfile, fieldnames=(
'Level', 'Date and Time', 'Source', 'Event ID', 'Task Category', 'Details',))
# 遍历读取的每一行
for row in list2:
# 如果 'Details' 字段为空,则跳过该行
if row['Details']==None:
continue
# 从 'Details' 字段中提取各种信息
Logon_Type = Logon_Type_rex.findall(row['Details']) # 登录类型
Account_Name = Account_Name_rex.findall(row['Details']) # 账户名称
Account_Domain = Account_Domain_rex.findall(row['Details']) # 账户域
Workstation_Name = Workstation_Name_rex.findall(row['Details']) # 工作站名称
Source_IP = Source_Network_Address_rex.findall(row['Details']) # 源网络地址
Logon_Process = Logon_Process_rex.findall(row['Details']) # 登录进程
Key_Length = Key_Length_rex.findall(row['Details']) # 密钥长度
Security_ID = Security_ID_rex.findall(row['Details']) # 安全 ID
Group_Name = Group_Name_rex.findall(row['Details']) # 组名称
Task_Name = Task_Name_rex.findall(row['Details']) # 任务名称
Task_Command = Task_Command_rex.findall(row['Details']) # 任务命令
Task_args = Task_args_rex.findall(row['Details']) # 任务参数
Process_Name = Process_Name_sec_rex.findall(row['Details']) # 进程名称
Category = Category_sec_rex.findall(row['Details']) # 类别
Subcategory = Subcategory_rex.findall(row['Details']) # 子类别
Changes = Changes_rex.findall(row['Details']) # 更改
Process_Command_Line = Process_Command_Line_rex.findall(row['Details']) # 进程命令行
Logon_Type = Logon_Type_rex.findall(row['Details'])
Account_Name = Account_Name_rex.findall(row['Details'])
Account_Domain = Account_Domain_rex.findall(row['Details'])
Workstation_Name = Workstation_Name_rex.findall(row['Details'])
Source_IP = Source_Network_Address_rex.findall(row['Details'])
Logon_Process = Logon_Process_rex.findall(row['Details'])
Key_Length = Key_Length_rex.findall(row['Details'])
Security_ID = Security_ID_rex.findall(row['Details'])
Group_Name = Group_Name_rex.findall(row['Details'])
Task_Name=Task_Name_rex.findall(row['Details'])
Task_Command = Task_Command_rex.findall(row['Details'])
Task_args= Task_args_rex.findall(row['Details'])
Process_Name=Process_Name_sec_rex.findall(row['Details'])
Category=Category_sec_rex.findall(row['Details'])
Subcategory=Subcategory_rex.findall(row['Details'])
Changes=Changes_rex.findall(row['Details'])
Process_Command_Line = Process_Command_Line_rex.findall(row['Details'])
#User Cretion using Net command
# 用户创建事件处理,使用 Net 命令
if row['Event ID']=="4688":
try:
# 检查事件详情中是否包含用户添加的命令
if len(re.findall('.*user.*/add.*',row['Details']))>0:
#print("test")
@ -283,9 +244,7 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
#print("User Name : ( %s ) "%Account_Name[0].strip(),end='')
#print("with Command Line : ( " + Process_Command_Line[0].strip()+" )")
# 生成事件描述
Event_desc ="User Name : ( %s ) "%Account_Name[0].strip()+"with Command Line : ( " + Process_Command_Line[0].strip()+" )"
# 将事件信息添加到 Security_events 数据结构中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Added using Net Command")
@ -296,7 +255,6 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r", " "))
#Detecting privielge Escalation using Token Elevation
# 检测特权提升尝试,使用命名管道
if len(re.findall(r"cmd.exe /c echo [a-z]{6} > \\\.\\pipe\\\w{1,10}",process_command_line))>0:
Event_desc ="User Name : ( %s ) " % user+"conducting NAMED PIPE privilege escalation with Command Line : ( " + process_command_line + " ) "
@ -309,7 +267,6 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r", " "))
# 检查进程命令行是否在可疑位置(如 temp、tmp、Program Data
if Process_Command_Line[0].strip().lower().find("\\temp\\")>-1 or Process_Command_Line[0].strip().lower().find("\\tmp\\")>-1 or Process_Command_Line[0].strip().lower().find("\\program data\\")>-1:
# print("test")
@ -328,7 +285,6 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r", " "))
# 检查是否存在可疑的可执行文件
for i in Suspicious_executables:
if Process_Command_Line[0].strip().lower().find(i.lower())>-1:
@ -348,7 +304,6 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r", " "))
# 检查是否存在可疑的 PowerShell 命令
for i in Suspicious_powershell_commands:
if Process_Command_Line[0].strip().lower().find(i.lower())>-1:
@ -370,21 +325,20 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
except:
# 捕获解析事件时的错误并输出错误信息
print("Error parsing below Event \n"+row['Details'])
continue
# User Created through management interface
# 检查事件 ID 是否为 "4720",表示创建用户事件
if row['Event ID']=="4720":
# 生成事件描述,包含用户名称和创建的用户名
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User Name ( " + Account_Name[0].strip() + " )", end='')
#print(" Created User Name ( " + Account_Name[1].strip()+ " )")
try:
Event_desc="User Name ( " + Account_Name[0].strip() + " )" + " Created User Name ( " + Account_Name[1].strip()+ " )"
except:
# 如果生成描述失败,使用默认描述
Event_desc="User Created a new user "
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Created through management interface")
@ -394,11 +348,13 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4609" 或 "1100",表示 Windows 关机事件
# Windows is shutting down
if row['Event ID']=="4609" or row['Event ID']=="1100":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User Name ( " + Account_Name[0].strip() + " )", end='')
#print(" Created User Name ( " + Account_Name[1].strip()+ " )")
Event_desc="Windows is shutting down "
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("Windows is shutting down")
@ -408,14 +364,24 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4732",表示用户被添加到本地组
# User added to local group
if row['Event ID']=="4732":
# 生成事件描述,包含用户名称和组名称
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) added User ( "+Security_ID[1].strip(), end='')
#print(" to local group ( " + Group_Name[0].strip() + " )")
try :
Event_desc="User ( " + Account_Name[0].strip() + " ) added User ( "+Account_Name[1].strip()+" to local group ( " + Group_Name[0].strip() + " )"
except:
Event_desc = "User ( " + Account_Name[0].strip() + " ) added User ( " + Security_ID[1].strip() + " to Global group ( " + Group_Name[0].strip() + " )"
# 将事件信息添加到 Security_events 列表中
Event_desc = "User ( " + Account_Name[0].strip() + " ) added User ( " + Security_ID[
1].strip() + " to Global group ( " + Group_Name[0].strip() + " )"
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User added to local group")
@ -425,14 +391,17 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4728",表示用户被添加到全局组
#add user to global group
if row['Event ID'] == "4728":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) added User ( "+Security_ID[1].strip(), end='')
#print(" to Global group ( " + Group_Name[0].strip() + " )")
try :
Event_desc="User ( " + Account_Name[0].strip() + " ) added User ( "+Account_Name[1].strip()+" to Global group ( " + Group_Name[0].strip() + " )"
except:
Event_desc = "User ( " + Account_Name[0].strip() + " ) added User ( " + Security_ID[1].strip() + " to Global group ( " + Group_Name[0].strip() + " )"
# 将事件信息添加到 Security_events 列表中
Event_desc = "User ( " + Account_Name[0].strip() + " ) added User ( " + Security_ID[
1].strip() + " to Global group ( " + Group_Name[0].strip() + " )"
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User added to global group")
@ -442,15 +411,20 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4756",表示用户被添加到通用组
#add user to universal group
if row['Event ID'] == "4756":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) added User ( "+Security_ID[1].strip(), end='')
Event_desc ="User ( " + Account_Name[0].strip() + " ) added User ( "+Security_ID[1].strip()
if len(Group_Name)>0:
#print(" to Universal group ( " + Group_Name[0].strip() + " )")
Event_desc=Event_desc+" to Universal group ( " + Group_Name[0].strip() + " )"
else:
Event_desc = Event_desc +" to Universal group ( " + Account_Name[1].strip() + " )"
# 将事件信息添加到 Security_events 列表中
#print(" to Universal group ( " + Account_Name[1].strip() + " )")
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User added to Universal group")
@ -460,15 +434,20 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4729",表示用户从全局组中移除
#remove user from global group
if row['Event ID'] == "4729":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip(), end='')
Event_desc ="User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip()
if len(Group_Name)>0:
#print(") from Global group ( " + Group_Name[0].strip() + " )")
Event_desc = Event_desc +") from Global group ( " + Group_Name[0].strip() + " )"
else:
Event_desc = Event_desc +") from Global group ( " + Account_Name[1].strip() + " )"
# 将事件信息添加到 Security_events 列表中
#print(") from Global group ( " + Account_Name[1].strip() + " )")
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Removed from Global Group")
@ -478,15 +457,18 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4757",表示用户从通用组中移除
#remove user from universal group
if row['Event ID'] == "4757":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip(), end='')
Event_desc ="User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip()
if len(Group_Name)>0:
#print(") from Universal group ( " + Group_Name[0].strip() + " )")
Event_desc = Event_desc+") from Universal group ( " + Group_Name[0].strip() + " )"
else:
#print(") from Universal group ( " + Account_Name[1].strip() + " )")
Event_desc = Event_desc +") from Universal group ( " + Account_Name[1].strip() + " )"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Removed from Universal Group")
@ -496,9 +478,8 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# 检查事件 ID 是否为 "4733",表示用户从本地组中移除
#remove user from local group
if row['Event ID'] == "4733":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip(), end='')
Event_desc ="User ( " + Account_Name[0].strip() + " ) removed User ( "+Security_ID[1].strip()
@ -508,7 +489,9 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
else:
#print(") from Local group ( " + Account_Name[1].strip() + " )")
Event_desc = Event_desc +") from Local group ( " + Account_Name[1].strip() + " )"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Removed from Local Group")
@ -518,8 +501,8 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#user removed group
# 用户从组中移除
if row['Event ID'] == "4730":
print("##### " + row['Date and Time'] + " #### ", end='')
print("User ( " + Account_Name[0].strip() + " ) removed Group ( ", end='')
@ -531,7 +514,7 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Event_desc = Event_desc +") from Local group ( " + Account_Name[0].strip() + " )"
#print(") from Local group ( " + Account_Name[0].strip() + " )")
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Removed Group")
@ -542,14 +525,12 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#user account removed
# 用户账户被移除
if row['Event ID'] == "4726":
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("User ( " + Account_Name[0].strip() + " ) removed user ", end='')
#print("( " + Account_Name[1].strip() + " )")
Event_desc ="User ( " + Account_Name[0].strip() + " ) removed user "+"( " + Account_Name[1].strip() + " )"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("User Account Removed")
@ -560,30 +541,24 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#Summary of process Execution
# 进程执行的总结
if row['Event ID']=="4688":
try:
# 检查进程命令行是否已在执行进程摘要中
if Process_Command_Line[0] not in Executed_Process_Summary[0]['Process Name']:
Executed_Process_Summary[0]['Process Name'].append(Process_Command_Line[0].strip())
Executed_Process_Summary[0]['Number of Execution'].append(1)
else :
# 如果已存在,则更新执行次数
Executed_Process_Summary[0]['Number of Execution'][Executed_Process_Summary[0]['Process Name'].index(Process_Command_Line[0].strip())]=Executed_Process_Summary[0]['Number of Execution'][Executed_Process_Summary[0]['Process Name'].index(Process_Command_Line[0].strip())]+1
except:
continue
# 检查事件 ID 是否为 "4625",表示登录失败事件
if row['Event ID'] == "4625" :
try:
# 检查用户是否已在安全认证摘要中
if Account_Name[1].strip() not in Security_Authentication_Summary[0]['User']:
Security_Authentication_Summary[0]['User'].append(Account_Name[1].strip())
Security_Authentication_Summary[0]['Number of Failed Logins'].append(1)
Security_Authentication_Summary[0]['Number of Successful Logins'].append(0)
else :
try:
# 更新失败登录次数
Security_Authentication_Summary[0]['Number of Failed Logins'][
Security_Authentication_Summary[0]['User'].index(Account_Name[1].strip())] = \
Security_Authentication_Summary[0]['Number of Failed Logins'][
@ -593,55 +568,44 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
print(Security_Authentication_Summary[0])
except:
continue
#password spray detection
# 密码喷洒检测
if row['Event ID'] == "4648" :
try:
# 检查账户名称是否在 PasswordSpray 字典中
if Account_Name[0].strip() not in PasswordSpray:
PasswordSpray[Account_Name[0].strip()]=[]
PasswordSpray[Account_Name[0].strip()].append(Account_Name[1].strip())
#else:
# PasswordSpray[Account_Name[0].strip()].append(Account_Name[1].strip())
# 检查第二个账户名称是否已在对应的 PasswordSpray 列表中
if Account_Name[1].strip() not in PasswordSpray[Account_Name[0].strip()] :
PasswordSpray[Account_Name[0].strip()].append(Account_Name[1].strip())
except:
continue
# 检查事件 ID 是否为 "4624",表示成功登录事件
#and (Logon_Type[0].strip()=="3" or Logon_Type[0].strip()=="10" or Logon_Type[0].strip()=="2" or Logon_Type[0].strip()=="8")
if row['Event ID'] == "4624" :
try:
#print(Account_Name[0])
# 检查用户是否已在安全认证摘要中
if Account_Name[1].strip() not in Security_Authentication_Summary[0]['User']:
Security_Authentication_Summary[0]['User'].append(Account_Name[1].strip())
Security_Authentication_Summary[0]['Number of Successful Logins'].append(1)
Security_Authentication_Summary[0]['Number of Failed Logins'].append(0)
else :
# 更新成功登录次数
Security_Authentication_Summary[0]['Number of Successful Logins'][
Security_Authentication_Summary[0]['User'].index(Account_Name[1].strip())] = \
Security_Authentication_Summary[0]['Number of Successful Logins'][
Security_Authentication_Summary[0]['User'].index(Account_Name[1].strip())] + 1
except:
continue
#detect pass the hash
# 检测哈希传递攻击
if row['Event ID'] == "4625" or row['Event ID'] == "4624":
# 检查登录类型和其他条件
if Logon_Type[0].strip() == "3" and Account_Name[1].strip() != "ANONYMOUS LOGON" and Account_Name[1].strip().find("$")==-1 and Logon_Process[0].strip() == "NtLmSsp" and Key_Length[0].strip() == "0":
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(
# "Pass the hash attempt Detected : user name ( %s ) domain name ( %s ) from IP ( %s ) and machine name ( %s )" % (
# Account_Name[1].strip(), Account_Domain[1].strip(), Source_IP[0].strip(), Workstation_Name[0].strip()))
# 生成事件描述
Event_desc ="Pass the hash attempt Detected : user name ( %s ) domain name ( %s ) from IP ( %s ) and machine name ( %s )" % (
Account_Name[1].strip(), Account_Domain[1].strip(), Source_IP[0].strip(), Workstation_Name[0].strip())
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("Pass the hash attempt Detected")
@ -652,17 +616,14 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#Audit log cleared
# 审计日志被清除
if row['Event ID'] == "517" or row['Event ID'] == "1102":
"""print("##### " + row['Date and Time'] + " #### ", end='')
print(
"Audit log cleared by user ( %s )" % (
Account_Name[0].strip()))
"""
# 生成事件描述
Event_desc = "Audit log cleared by user ( %s )" % (
Account_Name[0].strip())
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("Audit log cleared")
@ -673,16 +634,13 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#Suspicious Attempt to enumerate users or groups
# 可疑的用户或组枚举尝试
if row['Event ID'] == "4798" or row['Event ID'] == "4799" and row['Details'].find("System32\\svchost.exe")==-1:
"""print("##### " + row['Date and Time'] + " #### ", end='')
print(
"Suspicious Attempt to enumerate groups by user ( %s ) using process ( %s )" % (
Account_Name[0].strip(),Process_Name[0].strip()))
"""
# 生成事件描述
Event_desc ="Suspicious Attempt to enumerate groups by user ( %s ) using process ( %s )" % (Account_Name[0].strip(),Process_Name[0].strip())
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("Suspicious Attempt to enumerate groups")
@ -693,19 +651,17 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#System audit policy was changed
# 系统审计策略已更改
if row['Event ID'] == "4719" and len(Security_ID)>0 and Security_ID[0].strip()!="S-1-5-18" and Security_ID[0].strip()!="SYSTEM" :
"""print("##### " + row['Date and Time'] + " #### ", end='')
print(
"System audit policy was changed by user ( %s ) , Audit Policy category ( %s ) , Subcategory ( %s ) with changes ( %s )" % (
"System audit policy was changed by user ( %s ) , Audit Poricly category ( %s ) , Subcategory ( %s ) with changes ( %s )" % (
Account_Name[0].strip(),Category[0].strip(),Subcategory[0].strip(),Changes[0].strip()))
"""
try :
# 生成事件描述
Event_desc ="System audit policy was changed by user ( %s ) , Audit Policy category ( %s ) , Subcategory ( %s ) with changes ( %s )" % (Account_Name[0].strip(),Category[0].strip(),Subcategory[0].strip(),Changes[0].strip())
Event_desc ="System audit policy was changed by user ( %s ) , Audit Poricly category ( %s ) , Subcategory ( %s ) with changes ( %s )" % (Account_Name[0].strip(),Category[0].strip(),Subcategory[0].strip(),Changes[0].strip())
except :
Event_desc = "System audit policy was changed by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("System audit policy was changed")
@ -716,16 +672,14 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r", " "))
#scheduled task created
# 创建计划任务
if row['Event ID']=="4698" :
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("schedule task created by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0]))
try:
# 生成事件描述
Event_desc ="schedule task created by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0])
except:
Event_desc = "schedule task created by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("schedule task created")
@ -736,16 +690,14 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#scheduled task deleted
# 删除计划任务
if row['Event ID']=="1699" :
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("schedule task deleted by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0]))
try :
# 生成事件描述
Event_desc ="schedule task deleted by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0])
except:
Event_desc = "schedule task deleted by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("schedule task deleted")
@ -756,16 +708,14 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#schedule task updated
# 更新计划任务
if row['Event ID']=="4702" :
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("schedule task updated by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0]))
try:
# 生成事件描述
Event_desc ="schedule task updated by user ( %s ) with task name ( %s ) , Command ( %s ) and Argument ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0])
except:
Event_desc = "schedule task updated by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("schedule task updated")
@ -775,19 +725,15 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Event ID'].append(row['Event ID'])
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#schedule task enabled
# 启用计划任务
if row['Event ID']=="4700" :
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("schedule task enabled by user ( %s ) with task name ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0]))
try :
# 生成事件描述
Event_desc ="schedule task enabled by user ( %s ) with task name ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0])
except:
Event_desc = "schedule task enabled by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("schedule task enabled")
@ -798,17 +744,14 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
#schedule task disabled
# 禁用计划任务
if row['Event ID']=="4701" :
print("##### " + row['Date and Time'] + " #### ", end='')
#print("schedule task disabled by user ( %s ) with task name ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0]))
try :
# 生成事件描述
Event_desc ="schedule task disabled by user ( %s ) with task name ( %s ) " % ( Account_Name[0].strip(),Task_Name[0].strip(),Task_Command[0],Task_args[0])
except:
Event_desc = "schedule task disabled by user"
# 将事件信息添加到 Security_events 列表中
Security_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Security_events[0]['Detection Rule'].append("schedule task disabled")
@ -819,25 +762,16 @@ def detect_events_security_log(file_name='deep-blue-secuity.csv',winevent=False)
Security_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
for user in PasswordSpray:
# 检查用户的密码喷洒尝试次数是否超过3次
if len(PasswordSpray[user])>3:
# 生成事件描述
Event_desc = "Password Spray Detected by user ( "+user+" )"
# 将当前时间戳添加到事件列表中
Security_events[0]['Date and Time'].append(datetime.timestamp(datetime.now()))
Security_events[0]['timestamp'].append(datetime.timestamp(datetime.now()))
# 添加检测规则
Security_events[0]['Detection Rule'].append("Password Spray Detected")
# 添加检测领域
Security_events[0]['Detection Domain'].append("Threat")
# 添加事件严重性
Security_events[0]['Severity'].append("High")
# 添加事件描述
Security_events[0]['Event Description'].append(Event_desc)
# 添加事件ID
Security_events[0]['Event ID'].append("4648")
# 添加原始事件日志
Security_events[0]['Original Event Log'].append("User ( "+user+" ) did password spray attack using usernames ( "+",".join(PasswordSpray[user])+" )")
Security_events[0]['Original Event Log'].append("User ( "+user+" ) did password sparay attack using usernames ( "+",".join(PasswordSpray[user])+" )")
def detect_events_windows_defender_log(file_name='Defender-logs.csv',winevent=False):
@ -847,24 +781,20 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
else:
list = csv.DictReader(csvfile,fieldnames=("Details","Event ID","Version","Qualifiers","Level","Task","Opcode","Keywords","RecordId","ProviderName","ProviderId","LogName","ProcessId","ThreadId","MachineName","UserId","Date and Time","ActivityId","RelatedActivityId","ContainerLog","MatchedQueryIds","Bookmark","LevelDisplayName","OpcodeDisplayName","TaskDisplayName","KeywordsDisplayNames","Properties"))
"""
# 检查文件内容以确定使用的字段名
if open(file_name,"r").read(1000).find("\"Message\",\"Id\",\"Version\"")>0:
# 使用较长的字段名列表
list = csv.DictReader(csvfile, fieldnames=(
"Details", "Event ID", "Version", "Qualifiers", "Level", "Task", "Opcode", "Keywords", "RecordId",
"ProviderName", "ProviderId", "LogName", "ProcessId", "ThreadId", "MachineName", "UserId", "Date and Time",
"ActivityId", "RelatedActivityId", "ContainerLog", "MatchedQueryIds", "Bookmark", "LevelDisplayName",
"OpcodeDisplayName", "TaskDisplayName", "KeywordsDisplayNames", "Properties"))
else:
# 使用较短的字段名列表
list = csv.DictReader(csvfile, fieldnames=(
'Level', 'Date and Time', 'Source', 'Event ID', 'Task Category', 'Details',))
for row in list:
# 如果 'Details' 字段为空,则跳过该行
if row['Details']==None:
continue
# 从 'Details' 字段中提取信息
Name = Name_rex.findall(row['Details'])
Severity = Severity_rex.findall(row['Details'])
Category = Category_rex.findall(row['Details'])
@ -873,11 +803,11 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
Process_Name = Process_Name_rex.findall(row['Details'])
Action = Action_rex.findall(row['Details'])
# Windows Defender 对恶意软件采取了行动
#Windows Defender took action against Malware
if row['Event ID']=="1117" or row['Event ID']=="1007" :
# 生成事件描述
Event_desc = "Windows Defender took action against Malware - details : Severity ( %s ) , Name ( %s ) , Action ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) " % (Severity[0].strip(), Name[0].strip(), Action[0].strip(), Category[0].strip(), Path[0].strip(), Process_Name[0].strip(), User[0])
# 将事件信息添加到 Windows_Defender_events 列表中
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender took action against Malware - details : Severity ( %s ) , Name ( %s ) , Action ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Action[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0]))
Event_desc="Windows Defender took action against Malware - details : Severity ( %s ) , Name ( %s ) , Action ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Action[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0].strip())
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Windows_Defender_events[0]['Detection Rule'].append("Windows Defender took action against Malware")
@ -887,11 +817,13 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
Windows_Defender_events[0]['Event ID'].append(row['Event ID'])
Windows_Defender_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# Windows Defender 未能对恶意软件采取行动
#Windows Defender failed to take action against Malware
if row['Event ID']=="1118" or row['Event ID']=="1008" or row['Event ID']=="1119":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("Windows Defender failed to take action against Malware - details : Severity ( %s ) , Name ( %s ) , Action ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Action[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0]))
Event_desc="Windows Defender failed to take action against Malware - details : Severity ( %s ) , Name ( %s ) , Action ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Action[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0])
# 将事件信息添加到 Windows_Defender_events 列表中
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Windows_Defender_events[0]['Detection Rule'].append("Windows Defender failed to take action against Malware")
@ -901,11 +833,11 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
Windows_Defender_events[0]['Event ID'].append(row['Event ID'])
Windows_Defender_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
# Windows Defender 发现恶意软件
if row['Event ID'] == "1116" or row['Event ID']=="1006":
# 生成事件描述
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender Found Malware - details : Severity ( %s ) , Name ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0]))
Event_desc="Windows Defender Found Malware - details : Severity ( %s ) , Name ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0])
# 将事件信息添加到 Windows_Defender_events 列表中
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
Windows_Defender_events[0]['Detection Rule'].append("Windows Defender Found Malware")
@ -919,7 +851,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender deleted history of malwares - details : User ( %s ) "%(User[0]))
# Windows Defender 删除了恶意软件的历史记录 - 详细信息:用户
Event_desc=" Windows Defender deleted history of malwares - details : User ( %s ) "%(User[0])
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -934,7 +865,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender detected suspicious behavious Malware - details : Severity ( %s ) , Name ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0]))
# Windows Defender 检测到可疑行为的恶意软件 - 详细信息
Event_desc="Windows Defender detected suspicious behavior Malware - details : Severity ( %s ) , Name ( %s ) , Catgeory ( %s ) , Path ( %s ) , Process Name ( %s ) , User ( %s ) "%(Severity[0].strip(),Name[0].strip(),Category[0].strip(),Path[0].strip(),Process_Name[0].strip(),User[0])
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -949,7 +879,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print("Windows Defender real-time protection disabled")
# Windows Defender 实时保护已禁用
Event_desc="Windows Defender real-time protection disabled"
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -964,7 +893,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender real-time protection configuration changed")
# Windows Defender 实时保护配置已更改
Event_desc="Windows Defender real-time protection configuration changed"
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -979,7 +907,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender antimalware platform configuration changed")
# Windows Defender 反恶意软件平台配置已更改
Event_desc="Windows Defender antimalware platform configuration changed"
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -994,7 +921,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
#print("##### " + row['Date and Time'] + " #### ", end='')
#print(" Windows Defender scanning for malware is disabled")
# Windows Defender 扫描恶意软件已禁用
Event_desc="Windows Defender scanning for malware is disabled"
Windows_Defender_events[0]['Date and Time'].append(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p').isoformat())
Windows_Defender_events[0]['timestamp'].append(datetime.timestamp(datetime.strptime(row['Date and Time'],'%m/%d/%Y %I:%M:%S %p')))
@ -1005,7 +931,6 @@ def detect_events_windows_defender_log(file_name='Defender-logs.csv', winevent=F
Windows_Defender_events[0]['Event ID'].append(row['Event ID'])
Windows_Defender_events[0]['Original Event Log'].append(str(row['Details']).replace("\r"," "))
if row['Event ID'] == "5012" :
print("##### " + row['Date and Time'] + " #### ", end='')
print(" Windows Defender scanning for viruses is disabled")

File diff suppressed because one or more lines are too long

@ -1,31 +1,22 @@
import csv
import re
from netaddr import * # 导入netaddr库的所有内容用于处理网络地址
import xml.etree.ElementTree as ET # XML解析器
import pandas as pd # 数据分析库
from datetime import datetime, timezone # 日期时间处理
from evtx import PyEvtxParser # 解析Windows事件日志文件的库
from dateutil.parser import parse, isoparse # 解析日期时间字符串
from pytz import timezone # 处理时区
minlength = 1000 # 可能用于某个字符串长度的检查,但在这个文件中未使用
# 初始化一个字典列表,用于存储猎取的事件信息
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):
"""
解析并搜索Windows事件日志文件中的特定事件
参数:
- files: 要解析的事件日志文件列表
- str_regexes: 用于匹配事件数据的正则表达式列表
- eid: 事件ID如果提供则只搜索此ID的事件
- input_timzone: 输入日志的时区
- output: 输出文件名
- timestart, timeend: 搜索时间范围
"""
for file in files:
file=str(file)
print("Analyzing "+file)
@ -34,26 +25,35 @@ def Evtx_hunt(files, str_regexes, eid, input_timzone, output, timestart, timeend
except:
print("Issue analyzing "+file +"\nplease check if its not corrupted")
continue
try:
for record in parser.records():
try:
# 提取事件ID
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):
continue # 事件不在时间范围内,跳过
# 如果有EventID并且匹配eid如果eid不为None
if len(EventID) > 0 and (eid is None or EventID[0] == eid):
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'])
channel = Channel[0] if len(Channel) > 0 else " "
# 遍历所有提供的正则表达式
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)
@ -61,14 +61,11 @@ def Evtx_hunt(files, str_regexes, eid, input_timzone, output, timestart, timeend
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 : " + str(e)) # 修正了错误的打印函数调用
print("issue searching log : "+record['data']+"\n Error : "+print(e))
hunt_report(output)
def hunt_report(output):
"""
生成猎取事件的报告
参数:
- output: 输出CSV文件的前缀
"""
global Hunting_events
Events = pd.DataFrame(Hunting_events[0])
print("Found "+str(len(Hunting_events[0]["timestamp"]))+" Events")

@ -1,21 +1,22 @@
import json # 导入用于处理JSON数据的模块
import sqlite3 # 导入用于操作SQLite数据库的模块
import tempfile # 导入用于创建临时文件和目录的模块
import os # 导入用于操作系统功能的模块
import time # 导入用于处理时间相关功能的模块
import pandas as pd # 导入用于数据处理和分析的Pandas库
import geoip2.database # 导入用于GeoLite2数据库的GeoIP2库
import requests # 导入用于发送HTTP请求的模块
from dateutil import parser, tz # 导入用于解析和处理日期时间的模块
from pathlib import Path # 导入用于处理文件路径的模块
# 初始化全局变量用于计时
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
# SQL查询语句用于检测密码喷洒攻击
password_spray_query = '''
WITH FailedLogins AS (
SELECT
UserId,
ClientIP,
@ -24,6 +25,7 @@ password_spray_query = '''
events
WHERE
Operation = 'UserLoginFailed'
)
SELECT
UserId,
@ -31,6 +33,7 @@ SELECT
COUNT(DISTINCT ClientIP) AS UniqueIPCount,
COUNT(*) AS FailedLoginAttempts,
LoginDate
FROM
FailedLogins
GROUP BY
@ -42,7 +45,6 @@ ORDER BY
FailedLoginAttempts DESC;
'''
# SQL查询语句用于跟踪用户登录活动
user_logon_query = '''
SELECT
UserId,
@ -52,7 +54,7 @@ SELECT
SUM(CASE WHEN Operation = 'UserLoginFailed' THEN 1 ELSE 0 END) AS FailedLogins
FROM
events
WHERE
where
Operation = 'UserLoggedIn' OR Operation = 'UserLoginFailed'
GROUP BY
UserId,
@ -62,7 +64,6 @@ ORDER BY
UserId;
'''
# SQL查询语句用于统计用户执行的操作
User_operations_query = '''
SELECT
UserId,
@ -76,7 +77,6 @@ ORDER BY
OperationCount DESC;
'''
# SQL查询语句用于按天统计用户操作
user_operation_by_day_query = '''
SELECT
UserId,
@ -92,224 +92,175 @@ ORDER BY
OperationCount DESC
'''
def convert_csv(input_file,temp):
"""
将CSV文件转换为JSON格式的文件
参数:
- input_file: 输入的CSV文件路径
- temp: 临时目录路径
返回:
- json_file: 生成的JSON文件路径
"""
# 创建一个新的JSON文件路径结合临时目录和文件名
json_file = os.path.join(temp, 'audit_data.json')
# 同时打开输入的CSV文件进行读取和新的JSON文件进行写入设置编码为UTF-8
# 使用上下文管理器确保文件正确关闭
with open(input_file, 'r', encoding='utf-8') as csv_file, open(json_file, 'w', encoding='utf-8') as jsonl_file:
# 使用csv.DictReader来读取CSV文件每行会转换为字典
with open(input_file, 'r', encoding='utf-8') as csv_file:
# Create a CSV reader
reader = csv.DictReader(csv_file)
# 迭代读取CSV文件的每一行
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:
# 将CSV文件中'AuditData'字段的字符串解析为JSON对象
# Extract the AuditData which is already a JSON formatted string
json_data = json.loads(row['AuditData'])
# 将JSON对象再次转换为字符串
# Convert the JSON object back to a string to store in the file
json_string = json.dumps(json_data)
# 将转换后的JSON字符串写入json文件每行一个JSON对象以换行符结束
# Write the JSON string to the file with a newline
jsonl_file.write(json_string + '\n')
# 返回新创建的JSON文件的路径
return json_file
def flatten_json_file(input_file, timezone, chunk_size=10000):
"""
将JSON文件展平并处理时间戳
参数:
- input_file: 输入的JSON文件路径
- timezone: 目标时区
- chunk_size: 处理的块大小
返回:
- DataFrame: 展平后的数据
"""
# 初始化一个空列表用于存储数据块
# Read the JSON file in chunks
chunks = []
# 打开输入的JSON文件进行读取
with open(input_file, 'r') as file:
# 读取所有行到一个列表中
lines = file.readlines()
# 按块大小迭代处理行
for i in range(0, len(lines), chunk_size):
# 将当前块的每一行解析为JSON对象
chunk = [json.loads(line) for line in lines[i:i + chunk_size]]
# 处理每个记录
# Convert the CreationTime to the desired timezone
for record in chunk:
# 如果记录中包含'CreationTime'字段
if 'CreationTime' in record:
# 解析'CreationTime'字段为日期时间对象
# Parse the CreationTime
creation_time = parser.parse(record['CreationTime'])
# 如果日期时间对象没有时区信息设置为UTC
# 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())
# 将日期时间对象转换为目标时区并格式化为ISO格式字符串
# Convert the CreationTime to the desired timezone
record['CreationTime'] = creation_time.astimezone(timezone).isoformat()
# 将当前块展平并添加到数据块列表中
chunks.append(pd.json_normalize(chunk))
# 合并所有数据块为一个DataFrame并返回
return pd.concat(chunks, ignore_index=True)
# 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):
"""
从Pandas DataFrame创建SQLite数据库
参数:
- dataframe: 包含数据的Pandas DataFrame
- db_name: SQLite数据库文件名
"""
# 连接到SQLite数据库如果数据库不存在则会创建
conn = sqlite3.connect(db_name)
# 将DataFrame中的所有列转换为字符串类型
# Convert all columns to string
dataframe = dataframe.astype(str)
# 将DataFrame写入SQLite数据库中的'table'表,如果表已存在则替换
# 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):
"""
从文件中读取检测规则
conn.close()
参数:
- rule_file: 包含检测规则的JSON文件路径
返回:
- rules: 规则列表
"""
def read_detection_rules(rule_file):
with open(rule_file, 'r') as file:
return json.load(file)
def apply_detection_logic_sqlite(db_name, rules):
"""
应用检测逻辑到SQLite数据库
rules = json.load(file)
return rules
参数:
- db_name: SQLite数据库文件名
- rules: 检测规则列表
返回:
- DataFrame: 检测到的异常事件
"""
# 连接到SQLite数据库
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']
# 获取规则的SQL查询
query = rule['query']
# 执行SQL查询并将结果存储到DataFrame中
detected_events = pd.read_sql_query(query, conn)
# 添加规则名称列到DataFrame
detected_events['RuleName'] = rule_name
# 添加严重性列到DataFrame
detected_events['Severity'] = severity
# 将当前规则检测到的事件添加到列表中
all_detected_events.append(detected_events)
# 关闭数据库连接
conn.close()
# 合并所有检测到的事件为一个DataFrame并返回如果没有检测到事件则返回空DataFrame
return pd.concat(all_detected_events, ignore_index=True) if all_detected_events else pd.DataFrame()
def download_geolite_db(geolite_db_path):
"""
下载GeoLite2数据库用于IP地理定位
if all_detected_events:
result = pd.concat(all_detected_events, ignore_index=True)
else:
result = pd.DataFrame()
return result
参数:
- geolite_db_path: 保存GeoLite2数据库的路径
"""
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()
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):
"""
根据IP地址获取国家名称
参数:
- ip: IP地址
- reader: GeoLite2数据库的读取器
返回:
- str: 国家名称或'Unknown'如果无法解析
"""
try:
return reader.country(ip).country.name
response = reader.country(ip)
return response.country.name
except Exception as e:
print(f"Could not resolve IP {ip}: {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'):
"""
分析Office 365审计日志并生成报告
参数:
- auditfile: Office 365审计日志文件路径
- rule_file: 检测规则文件路径
- output: 输出目录
- timezone: 目标时区
- include_flattened_data: 是否包含展平后的数据
- geolite_db_path: GeoLite2数据库文件路径
"""
global start_time, end_time # 声明全局变量start_time和end_time
start_time = time.time() # 记录开始时间
temp_dir = ".temp" # 设置临时目录路径
if output is None or output == "": # 如果输出目录未指定或为空
output = os.path.splitext(auditfile)[0] # 使用审计文件的基础名称作为输出目录
start_time = time.time()
temp_dir = ".temp"
if output is None or output == "":
output = os.path.splitext(auditfile)[0]
try:
os.makedirs(output, exist_ok=True) # 创建输出目录,如果不存在则创建
os.makedirs(temp_dir, exist_ok=True) # 创建临时目录,如果不存在则创建
if not os.path.exists(geolite_db_path): # 如果GeoLite2数据库文件不存在
download_geolite_db(geolite_db_path) # 下载GeoLite2数据库
json_file = convert_csv(auditfile, temp_dir) # 将CSV文件转换为JSON文件
input_file = json_file # 设置输入文件路径为转换后的JSON文件
db_name = os.path.join(temp_dir, 'audit_data.db') # 设置SQLite数据库文件路径
if rule_file is None: # 如果规则文件未指定
rule_file = 'O365_detection_rules.json' # 使用默认的规则文件名
output_file = f"{output}_o365_report.xlsx" # 设置输出的Excel报告文件路径
# 展平JSON数据并处理时间戳
# 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)
# 创建SQLite数据库
# Create SQLite database from the flattened DataFrame
create_sqlite_db_from_dataframe(flattened_df, db_name)
# 使用GeoLite2数据库解析IP地址
# 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)
# 重新排序DataFrame列以便RuleName在前
# 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']]
columns = ['RuleName', 'Severity'] + [col for col in detected_events.columns if
col not in ['RuleName', 'Severity']]
detected_events = detected_events[columns]
# 执行其他SQL查询
# 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)
@ -318,19 +269,20 @@ def analyzeoff365(auditfile, rule_file, output, timezone, include_flattened_data
finally:
conn.close()
# 生成Excel报告
# 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)
@ -341,8 +293,10 @@ def analyzeoff365(auditfile, rule_file, output, timezone, include_flattened_data
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')
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")
@ -350,12 +304,18 @@ def analyzeoff365(auditfile, rule_file, output, timezone, include_flattened_data
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()
os.rmdir(temp_dir)
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

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

@ -1,107 +1,101 @@
# 尝试创建一个名为 "wineventlog" 的目录
try{
New-Item -ItemType "directory" -Path "wineventlog"
}
catch {
# 如果创建目录失败,输出错误信息
catch
{
echo "can't create a new directory"
}
# 尝试获取安全日志并导出为 CSV 文件
try{
get-eventlog -log Security | export-csv wineventlog/Security.csv
}
catch {
# 如果获取安全日志失败,输出错误信息
catch
{
echo "Can't retrieve Security Logs"
}
# 尝试获取系统日志并导出为 CSV 文件
try {
try
{
Get-WinEvent -LogName System | export-csv wineventlog/System.csv
}
catch {
# 如果获取系统日志失败,输出错误信息
catch
{
echo "Can't retrieve System Logs"
}
# 尝试获取应用程序日志并导出为 CSV 文件
try{
Get-WinEvent -LogName Application | export-csv wineventlog/Application.csv
}
catch {
# 如果获取应用程序日志失败,输出错误信息
catch
{
echo "Can't retrieve Application Logs"
}
# 尝试获取 Windows PowerShell 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName "Windows PowerShell" | export-csv wineventlog/Windows_PowerShell.csv
}
catch {
# 如果获取 Windows PowerShell 日志失败,输出错误信息
catch
{
echo "Can't retrieve Windows PowerShell Logs"
}
# 尝试获取 Microsoft-Windows-TerminalServices-LocalSessionManager/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | export-csv wineventlog/LocalSessionManager.csv
}
catch {
# 如果获取 LocalSessionManager 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-TerminalServices-LocalSessionManager/Operational Logs"
}
# 尝试获取 Microsoft-Windows-Windows Defender/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" | export-csv wineventlog/Windows_Defender.csv
}
catch {
# 如果获取 Windows Defender 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-Windows Defender/Operational Logs"
}
# 尝试获取 Microsoft-Windows-TaskScheduler/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational | export-csv wineventlog/TaskScheduler.csv
}
catch {
# 如果获取 TaskScheduler 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-TaskScheduler/Operational Logs"
}
# 尝试获取 Microsoft-Windows-WinRM/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName Microsoft-Windows-WinRM/Operational | export-csv wineventlog/WinRM.csv
}
catch {
# 如果获取 WinRM 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-WinRM/Operational Logs"
}
# 尝试获取 Microsoft-Windows-Sysmon/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName Microsoft-Windows-Sysmon/Operational | export-csv wineventlog/Sysmon.csv
}
catch {
# 如果获取 Sysmon 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-Sysmon/Operational Logs"
}
# 尝试获取 Microsoft-Windows-PowerShell/Operational 日志并导出为 CSV 文件
try{
Get-WinEvent -LogName Microsoft-Windows-PowerShell/Operational | export-csv wineventlog/Powershell_Operational.csv
}
catch {
# 如果获取 PowerShell Operational 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-PowerShell/Operational Logs"
}
# 尝试压缩 "wineventlog" 目录为 logs.zip
try {
try
{
Compress-Archive -Path wineventlog -DestinationPath ./logs.zip
}
catch {
# 如果压缩失败,输出错误信息
echo "couldn't compress the log folder"
catch
{
echo "couldn't compress the the log folder "
}

@ -1,107 +1,101 @@
# 尝试创建一个名为 "wineventlog" 的目录
try{
New-Item -ItemType "directory" -Path "wineventlog"
}
catch {
# 如果创建目录失败,输出错误信息
catch
{
echo "can't create a new directory"
}
# 尝试导出安全日志到指定的 EVTX 文件
try{
wevtutil epl Security wineventlog/Security.evtx
}
catch {
# 如果导出安全日志失败,输出错误信息
catch
{
echo "Can't retrieve Security Logs"
}
# 尝试导出系统日志到指定的 EVTX 文件
try {
try
{
wevtutil epl System wineventlog/System.evtx
}
catch {
# 如果导出系统日志失败,输出错误信息
catch
{
echo "Can't retrieve System Logs"
}
# 尝试导出应用程序日志到指定的 EVTX 文件
try{
wevtutil epl Application wineventlog/Application.evtx
}
catch {
# 如果导出应用程序日志失败,输出错误信息
catch
{
echo "Can't retrieve Application Logs"
}
# 尝试导出 Windows PowerShell 日志到指定的 EVTX 文件
try{
wevtutil epl "Windows PowerShell" wineventlog/Windows_PowerShell.evtx
}
catch {
# 如果导出 Windows PowerShell 日志失败,输出错误信息
catch
{
echo "Can't retrieve Windows PowerShell Logs"
}
# 尝试导出 Microsoft-Windows-TerminalServices-LocalSessionManager/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" wineventlog/LocalSessionManager.evtx
}
catch {
# 如果导出 LocalSessionManager 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-TerminalServices-LocalSessionManager/Operational Logs"
}
# 尝试导出 Microsoft-Windows-Windows Defender/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl "Microsoft-Windows-Windows Defender/Operational" wineventlog/Windows_Defender.evtx
}
catch {
# 如果导出 Windows Defender 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-Windows Defender/Operational Logs"
}
# 尝试导出 Microsoft-Windows-TaskScheduler/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl Microsoft-Windows-TaskScheduler/Operational wineventlog/TaskScheduler.evtx
}
catch {
# 如果导出 TaskScheduler 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-TaskScheduler/Operational Logs"
}
# 尝试导出 Microsoft-Windows-WinRM/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl Microsoft-Windows-WinRM/Operational wineventlog/WinRM.evtx
}
catch {
# 如果导出 WinRM 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-WinRM/Operational Logs"
}
# 尝试导出 Microsoft-Windows-Sysmon/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl Microsoft-Windows-Sysmon/Operational wineventlog/Sysmon.evtx
}
catch {
# 如果导出 Sysmon 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-Sysmon/Operational Logs"
}
# 尝试导出 Microsoft-Windows-PowerShell/Operational 日志到指定的 EVTX 文件
try{
wevtutil epl Microsoft-Windows-PowerShell/Operational wineventlog/Powershell_Operational.evtx
}
catch {
# 如果导出 PowerShell Operational 日志失败,输出错误信息
catch
{
echo "Can't retrieve Microsoft-Windows-PowerShell/Operational Logs"
}
# 尝试压缩 "wineventlog" 目录为 logs.zip
try {
try
{
Compress-Archive -Path wineventlog -DestinationPath ./logs.zip
}
catch {
# 如果压缩失败,输出错误信息
echo "couldn't compress the log folder"
catch
{
echo "couldn't compress the the log folder "
}

@ -0,0 +1,38 @@
一、源代码结构与功能
APT-Hunter的源代码主要由Python编写包含多个模块和脚本用于实现日志收集、解析、分析以及结果输出等功能。
日志收集:
源代码中包含了用于收集Windows事件日志的PowerShell脚本windows-log-collector-full-v3-CSV && windows-log-collector-full-v3-EVTX脚本能够提取CSV和EVTX格式的日志。
用户可以通过运行这些脚本来自动收集所需的日志,而无需手动查找和提取。
日志解析:
APT-Hunter使用内置库如csv库来解析CSV日志文件使用外部库如evtx库来解析EVTX日志文件。
解析过程中APT-Hunter会使用正则表达式Regex为每个事件提取字段以便后续分析。
日志分析:
源代码中包含了用于分析日志的逻辑这些逻辑基于Mitre ATT&CK战术和技术将攻击指标映射到Windows事件日志中。
分析过程中APT-Hunter会检测各种可疑活动如恶意软件的安装、未授权的网络连接等并生成相应的报告。
结果输出:
分析结果可以以Excel工作表和CSV文件的形式输出便于用户查看和分析。
其中Excel工作表包含了从每个Windows日志中检测到的所有事件而CSV文件则可以用于时间线分析。
二、关键模块与代码分析
日志收集模块:
该模块主要包含PowerShell脚本用于从Windows系统中提取日志。
脚本中使用了Windows事件日志API或PowerShell命令来获取日志数据并将其保存为CSV或EVTX格式。
日志解析模块:
该模块使用Python编写包含了用于解析CSV和EVTX日志文件的函数。
在解析CSV文件时使用了Python的csv库来读取文件并提取字段。
在解析EVTX文件时使用了外部库如pyevtx来读取文件并解析事件。
日志分析模块:
该模块是APT-Hunter的核心部分包含了用于检测可疑活动的逻辑。
逻辑中定义了多个检测规则这些规则基于Mitre ATT&CK战术和技术用于识别各种APT攻击指标。
分析过程中APT-Hunter会遍历日志文件中的事件并根据检测规则进行判断和分类。
结果输出模块:
该模块负责将分析结果输出为用户可读的格式。
在输出Excel工作表时使用了Python的pandas库来创建和填充工作表。
在输出CSV文件时则直接使用了Python的文件操作函数来写入数据。
三、技术亮点与优势
高效性APT-Hunter能够快速地收集、解析和分析大量的Windows事件日志提高了威胁检测的效率和准确性。
易用性:该工具提供了友好的用户界面和简洁的操作流程,使得用户能够轻松上手并快速掌握其使用方法。
兼容性APT-Hunter支持多种格式的日志解析和输出配置使得用户能够灵活地将其集成到现有的安全监控系统中。
开源性作为一款开源工具APT-Hunter的源代码是公开的用户可以根据需要进行二次开发或定制。
四、结论与展望
通过对APT-Hunter源代码的分析可以看出该工具在Windows事件日志的威胁搜寻方面具有较高的效率和准确性。其友好的用户界面、简洁的操作流程以及灵活的日志解析和输出配置使得用户能够轻松地使用该工具进行威胁检测和分析。然而随着APT攻击的不断发展和变化APT-Hunter也需要不断更新和完善其检测规则和功能以应对新的威胁和挑战。未来可以进一步优化APT-Hunter的性能和效率提高其适用性和易用性并探索与其他安全监控系统的集成和联动以实现更加全面和高效的安全防护。
Loading…
Cancel
Save