-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityMonitor.ps1
More file actions
1613 lines (1496 loc) · 76.5 KB
/
Copy pathSecurityMonitor.ps1
File metadata and controls
1613 lines (1496 loc) · 76.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
param(
[string]$ConfigPath = ".\SecurityMonitor-Config.json",
[string]$LogPath = "",
[switch]$SetupAudit,
[switch]$InstallSysmon,
[switch]$RunOnce,
[switch]$TestMode,
[switch]$NonInteractive,
[switch]$JsonLog,
[string]$JsonLogPath = "",
[int]$MinSeverity = 0,
[int]$CheckInterval = 60
)
function New-EventList { return [System.Collections.Generic.List[object]]::new() }
function ConvertTo-Hashtable {
param([Parameter(ValueFromPipeline)]$InputObject)
process {
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {
$collection = @(foreach ($obj in $InputObject) { ConvertTo-Hashtable $obj })
return , $collection
}
if ($InputObject -is [psobject]) {
$hash = @{}
foreach ($prop in $InputObject.PSObject.Properties) {
$hash[$prop.Name] = ConvertTo-Hashtable $prop.Value
}
return $hash
}
return $InputObject
}
}
$Script:HasSysmon = $false
$Script:IsDomainController = $false
$Script:SysmonLogName = "Microsoft-Windows-Sysmon/Operational"
$Script:SIDCache = @{}
$Script:JsonLogFilePath = ""
function Detect-Capabilities {
# Check Sysmon
try {
$svc = Get-Service -Name "Sysmon*" -ErrorAction SilentlyContinue
if ($svc -and $svc.Status -eq "Running") {
$Script:HasSysmon = $true
Write-Host "[OK] Sysmon detected and running" -ForegroundColor Green
}
else {
Write-Host "[--] Sysmon not running (Sysmon events will be skipped)" -ForegroundColor Yellow
}
}
catch { Write-Host "[--] Sysmon not available" -ForegroundColor Yellow }
# Check if Domain Controller
try {
$dcRole = (Get-WmiObject Win32_ComputerSystem -ErrorAction SilentlyContinue).DomainRole
if ($dcRole -ge 4) {
$Script:IsDomainController = $true
Write-Host "[OK] Domain Controller detected — AD events enabled" -ForegroundColor Green
}
else {
Write-Host "[--] Not a DC (AD-specific events will be skipped)" -ForegroundColor Yellow
}
}
catch { Write-Host "[--] Could not determine DC role" -ForegroundColor Yellow }
}
$Script:Config = @{
EventIDs = @{
Logon = @(4624, 4625, 4648, 4672, 4627, 4634, 4647, 4768, 4769, 4771, 4776)
Process = @(4688, 4689, 4696)
File = @(4660, 4661, 4663, 4656, 4658, 4699, 4654, 4670)
Account = @(4720, 4722, 4724, 4726, 4728, 4732, 4733, 4756, 4735, 4737, 4740, 4767, 4782)
Service = @(7045, 4697, 7034, 7035, 7036, 7040)
Policy = @(4719, 4738, 4904, 4905, 4907, 4912)
Network = @(5156, 5157, 5158, 5159)
ScheduledTask = @(4698, 4700, 4701, 4702)
ScheduledTaskOperational = @(106, 140, 141, 200, 201)
PowerShell = @(4103, 4104, 4105, 4106)
ObjectAccess = @(4654, 4670, 4907)
Registry = @(4657)
AD = @(4662, 4742, 4780, 4781, 5136, 5137, 5138, 5139, 5141)
Kerberos = @(4768, 4769, 4771, 4776)
}
SysmonEventIDs = @(1, 3, 5, 7, 8, 10, 11, 12, 13, 15, 17, 18, 22, 23, 25)
SuspiciousProcesses = @(
"cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe",
"mshta.exe", "rundll32.exe", "regsvr32.exe", "certutil.exe",
"bitsadmin.exe", "wmic.exe", "schtasks.exe", "at.exe",
"msiexec.exe", "installutil.exe", "regasm.exe", "regsvcs.exe",
"msbuild.exe", "cmstp.exe", "msxsl.exe", "nltest.exe",
"esentutl.exe", "expand.exe", "extrac32.exe",
"net.exe", "net1.exe", "whoami.exe", "hostname.exe",
"systeminfo.exe", "tasklist.exe", "sc.exe", "reg.exe",
"bcdedit.exe", "vssadmin.exe", "wbadmin.exe", "ntdsutil.exe",
"procdump.exe", "procdump64.exe", "mimikatz.exe",
"psexec.exe", "psexec64.exe", "rubeus.exe", "sharphound.exe"
)
NoiseFilters = @{
Users = @("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE", "SERVICE")
Paths = @("SRU.chk", "LogFiles", "wbem", "Microsoft\\\\Windows\\\\PowerShell", "Microsoft\\\\Windows\\\\AppReadiness")
}
BruteForceThreshold = 5
LookbackMinutes = 5
SystemName = $env:COMPUTERNAME
Domain = "YOURORG.COM"
WMIWhitelist = @("SCM Event Log Filter", "SCM Event Log Consumer", "BVTFilter")
}
Write-Host "===================================================================" -ForegroundColor Cyan
Write-Host "POWERSHELL SECURITY MONITOR v2.0" -ForegroundColor Cyan
Write-Host "===================================================================" -ForegroundColor Cyan
Write-Host ""
Detect-Capabilities
Write-Host ""
if (-not (Test-Path $ConfigPath)) {
Write-Host "Config file not found at: $ConfigPath" -ForegroundColor Yellow
}
else {
Write-Host "Config file found at: $ConfigPath" -ForegroundColor Green
}
if (-not $NonInteractive) {
$newConfigPath = Read-Host "Enter config file path (or press Enter to use: $ConfigPath)"
}
else { $newConfigPath = "" }
if (-not [string]::IsNullOrWhiteSpace($newConfigPath)) { $ConfigPath = $newConfigPath }
if (Test-Path $ConfigPath) {
try {
$loaded = Get-Content $ConfigPath -Raw | ConvertFrom-Json | ConvertTo-Hashtable
# Merge loaded config into defaults (loaded values override defaults)
foreach ($key in $loaded.Keys) {
$Script:Config[$key] = $loaded[$key]
}
Write-Host "[OK] Loaded configuration from: $ConfigPath" -ForegroundColor Green
}
catch {
Write-Host "[X] Error loading config: $($_.Exception.Message). Using defaults." -ForegroundColor Red
}
}
else {
Write-Host "[--] Config file not found. Using default configuration." -ForegroundColor Yellow
}
Write-Host ""
$defaultLogPath = ".\SecurityMonitor_$(Get-Date -Format 'yyyyMMdd').log"
if ([string]::IsNullOrWhiteSpace($LogPath)) {
Write-Host "Log file path not specified." -ForegroundColor Yellow
}
else {
Write-Host "Log file path specified: $LogPath" -ForegroundColor Green
}
if (-not $NonInteractive) {
$userLogPath = Read-Host "Enter log file path (or press Enter for default: $defaultLogPath)"
}
else { $userLogPath = "" }
if (-not [string]::IsNullOrWhiteSpace($userLogPath)) {
$LogPath = $userLogPath
}
elseif ([string]::IsNullOrWhiteSpace($LogPath)) {
$LogPath = $defaultLogPath
}
Write-Host ""
$defaultVerifyPath = ".\Verify-AuditPolicies.ps1"
if (-not (Test-Path $defaultVerifyPath)) {
Write-Host "Verify script not found at: $defaultVerifyPath" -ForegroundColor Yellow
}
else {
Write-Host "Verify script found at: $defaultVerifyPath" -ForegroundColor Green
}
if (-not $NonInteractive) {
$verifyPath = Read-Host "Enter verify script path (or press Enter for default: $defaultVerifyPath)"
}
else { $verifyPath = "" }
if ([string]::IsNullOrWhiteSpace($verifyPath)) { $verifyPath = $defaultVerifyPath }
$Script:VerifyScriptPath = $verifyPath
$logDirectory = Split-Path -Path $LogPath -Parent
if (-not [string]::IsNullOrWhiteSpace($logDirectory) -and -not (Test-Path $logDirectory)) {
try {
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
Write-Host "[OK] Created log directory: $logDirectory" -ForegroundColor Green
}
catch {
Write-Host "[X] Could not create log directory. Logs screen-only." -ForegroundColor Yellow
$LogPath = ""
}
}
$Script:LogFilePath = $LogPath
Write-Host "[OK] Log file: $LogPath" -ForegroundColor Green
Write-Host "===================================================================" -ForegroundColor Cyan
Write-Host ""
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"WARNING" { "Yellow" }
"ERROR" { "Red" }
"SUCCESS" { "Green" }
"CRITICAL" { "Red" }
default { "White" }
}
Write-Host "[$timestamp] " -NoNewline -ForegroundColor Gray
Write-Host "[$Level] " -NoNewline -ForegroundColor $color
Write-Host $Message
if ($Script:LogFilePath -and -not [string]::IsNullOrWhiteSpace($Script:LogFilePath)) {
try { Add-Content -Path $Script:LogFilePath -Value "[$timestamp] [$Level] $Message" -ErrorAction SilentlyContinue } catch {}
}
}
function Get-SeverityScore {
param([hashtable]$Event, [array]$Reasons)
$score = 1
# Base scores by event type
if ($Event.EventID -in @(4625)) { $score = [Math]::Max($score, 4) }
if ($Event.EventID -in @(4720, 4722, 4724, 4726, 4728, 4732, 4756)) { $score = [Math]::Max($score, 6) }
if ($Event.EventID -in @(4698, 7045, 4697)) { $score = [Math]::Max($score, 5) }
if ($Event.EventID -in @(1102, 104)) { $score = [Math]::Max($score, 9) }
if ($Event.Source -eq "WMI Persistence") { $score = [Math]::Max($score, 8) }
if ($Event.Source -eq "Sysmon" -and $Event.EventID -eq 8) { $score = [Math]::Max($score, 8) }
if ($Event.Source -eq "Sysmon" -and $Event.EventID -eq 10) { $score = [Math]::Max($score, 7) }
# Boost for specific indicators
foreach ($r in $Reasons) {
if ($r -match "Brute force|DCSync|DCShadow|Golden Ticket|credential dump|LSASS") { $score = [Math]::Max($score, 9) }
if ($r -match "Kerberoast|AS-REP|lateral movement") { $score = [Math]::Max($score, 7) }
if ($r -match "Suspicious process|PowerShell command") { $score = [Math]::Max($score, 5) }
if ($r -match "Log cleared|Defender.*tamper|disabled") { $score = [Math]::Max($score, 9) }
}
# Admin activity boost
if ($Event.User -match "Administrator|Admin" -and $score -ge 4) { $score = [Math]::Min($score + 1, 10) }
# External IP boost
if ($Event.IPAddress -and $Event.IPAddress -ne "N/A" -and $Event.IPAddress -ne "-" -and
$Event.IPAddress -ne "127.0.0.1" -and $Event.IPAddress -ne "::1" -and
$Event.IPAddress -notmatch "^192\.168\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.") {
$score = [Math]::Min($score + 2, 10)
}
return [Math]::Min($score, 10)
}
function Get-SeverityLabel {
param([int]$Score)
switch ($Score) {
{ $_ -le 3 } { return "INFORMATIONAL" }
{ $_ -le 5 } { return "LOW" }
{ $_ -le 7 } { return "MEDIUM" }
{ $_ -le 9 } { return "HIGH" }
default { return "CRITICAL" }
}
}
function Write-JsonLog {
param([hashtable]$Event, [int]$Severity, [string]$SeverityLabel, [array]$Reasons)
if (-not $JsonLog -or -not $Script:JsonLogFilePath) { return }
try {
$obj = [ordered]@{
timestamp = (Get-Date -Format "yyyy-MM-ddTHH:mm:ss.fffZ")
severity = $Severity
severity_label = $SeverityLabel
event_id = $Event.EventID
source = $Event.Source
machine = $Event.Machine
user = $Event.User
ip_address = $Event.IPAddress
process = $Event.ProcessName
file_path = $Event.FilePath
flags = $Reasons
message = ($Event.Message -split "`n" | Select-Object -First 2) -join " | "
}
$json = $obj | ConvertTo-Json -Compress
Add-Content -Path $Script:JsonLogFilePath -Value $json -ErrorAction SilentlyContinue
}
catch {}
}
# Setup JSON log path
if ($JsonLog) {
if ([string]::IsNullOrWhiteSpace($JsonLogPath)) {
$Script:JsonLogFilePath = ".\SecurityMonitor_$(Get-Date -Format 'yyyyMMdd').jsonl"
}
else {
$Script:JsonLogFilePath = $JsonLogPath
}
Write-Host "[OK] JSON log: $($Script:JsonLogFilePath)" -ForegroundColor Green
}
# Apply MinSeverity from config if not set via parameter
if ($MinSeverity -eq 0) {
if ($Script:Config.MinSeverity) { $MinSeverity = $Script:Config.MinSeverity }
else { $MinSeverity = 1 }
}
function Get-EventField {
param(
[System.Diagnostics.Eventing.Reader.EventLogRecord]$Event,
[string]$FieldName
)
try {
$xml = [xml]$Event.ToXml()
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event")
# Fix: use Data[@Name='...'] for EventData fields
$field = $xml.SelectSingleNode("//ns:Data[@Name='$FieldName']", $ns)
if ($field) { return $field.InnerText }
# Fallback: try direct element (for System fields)
$field = $xml.SelectSingleNode("//ns:$FieldName", $ns)
if ($field) { return $field.InnerText }
}
catch {}
return $null
}
function Get-UserFromSID {
param([string]$SID)
if ([string]::IsNullOrWhiteSpace($SID) -or $SID -eq "-") { return "N/A" }
try {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($SID)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
return $objUser.Value
}
catch { return $SID }
}
function Install-Sysmon {
Write-Log "Installing Sysmon..." "INFO"
$sysmonExe = ".\Sysmon.exe"
$sysmonConfig = ".\sysmonconfig.xml"
$sysmonUrl = "https://live.sysinternals.com/Sysmon.exe"
$configUrl = "https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml"
# Check if already running
$existingSvc = Get-Service -Name "Sysmon*" -ErrorAction SilentlyContinue
if ($existingSvc -and $existingSvc.Status -eq "Running") {
Write-Log "Sysmon is already installed and running." "SUCCESS"
$update = Read-Host "Update config? (y/N)"
if ($update -ne "y") { return }
}
# Download if needed
if (-not (Test-Path $sysmonExe)) {
Write-Log "Downloading Sysmon.exe..." "INFO"
try {
Invoke-WebRequest -Uri $sysmonUrl -OutFile $sysmonExe -UseBasicParsing -ErrorAction Stop
Write-Log "Downloaded Sysmon.exe" "SUCCESS"
}
catch {
Write-Log "Failed to download Sysmon. Place Sysmon.exe manually in $(Get-Location)" "ERROR"
return
}
}
if (-not (Test-Path $sysmonConfig)) {
Write-Log "Downloading SwiftOnSecurity Sysmon config..." "INFO"
try {
Invoke-WebRequest -Uri $configUrl -OutFile $sysmonConfig -UseBasicParsing -ErrorAction Stop
Write-Log "Downloaded sysmonconfig.xml" "SUCCESS"
}
catch {
Write-Log "Failed to download config. Place sysmonconfig.xml manually." "ERROR"
return
}
}
# Install or update
try {
if ($existingSvc) {
Write-Log "Updating Sysmon config..." "INFO"
& $sysmonExe -c $sysmonConfig 2>&1 | Out-Null
}
else {
Write-Log "Installing Sysmon service..." "INFO"
& $sysmonExe -accepteula -i $sysmonConfig 2>&1 | Out-Null
}
Start-Sleep -Seconds 2
$svc = Get-Service -Name "Sysmon*" -ErrorAction SilentlyContinue
if ($svc -and $svc.Status -eq "Running") {
$Script:HasSysmon = $true
Write-Log "Sysmon installed and running!" "SUCCESS"
}
else {
Write-Log "Sysmon service not detected after install. Check manually." "WARNING"
}
}
catch {
Write-Log "Sysmon install failed: $($_.Exception.Message)" "ERROR"
}
}
if ($InstallSysmon) {
Install-Sysmon
if (-not $SetupAudit -and $RunOnce -eq $false) { exit 0 }
}
function Get-EventDetails {
param([System.Diagnostics.Eventing.Reader.EventLogRecord]$Event)
$details = @{
Time = $Event.TimeCreated; EventID = $Event.Id; Level = $Event.LevelDisplayName
Source = $Event.ProviderName; Machine = $Event.MachineName; Message = $Event.Message
User = "N/A"; IPAddress = "N/A"; ProcessName = "N/A"; FilePath = "N/A"
AccessMask = "N/A"; RecordId = $Event.RecordId; Reasons = @()
}
try {
switch ($Event.Id) {
{ $_ -in @(4624, 4625) } {
$details.User = Get-EventField -Event $Event -FieldName "TargetUserName"
$details.IPAddress = Get-EventField -Event $Event -FieldName "IpAddress"
if (-not $details.User -or $details.User -eq "N/A") {
$sid = Get-EventField -Event $Event -FieldName "TargetUserSid"
if ($sid) { $details.User = Get-UserFromSID -SID $sid }
}
}
4688 {
$details.ProcessName = Get-EventField -Event $Event -FieldName "NewProcessName"
$details.FilePath = $details.ProcessName
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
$cmdLine = Get-EventField -Event $Event -FieldName "CommandLine"
if ($cmdLine) { $details.Message += " | Command: $cmdLine" }
if (-not $details.User -or $details.User -eq "N/A") {
$sid = Get-EventField -Event $Event -FieldName "SubjectUserSid"
if ($sid) { $details.User = Get-UserFromSID -SID $sid }
}
}
{ $_ -in @(4663, 4660, 4654, 4670) } {
$details.FilePath = Get-EventField -Event $Event -FieldName "ObjectName"
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
if ($_ -eq 4663) {
$details.AccessMask = Get-EventField -Event $Event -FieldName "AccessMask"
$accesses = Get-EventField -Event $Event -FieldName "Accesses"
if ($accesses) { $details.Message += " | Access: $accesses" }
}
if (-not $details.User -or $details.User -eq "N/A") {
$sid = Get-EventField -Event $Event -FieldName "SubjectUserSid"
if ($sid) { $details.User = Get-UserFromSID -SID $sid }
}
}
4657 {
$details.FilePath = Get-EventField -Event $Event -FieldName "ObjectName"
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
$val = Get-EventField -Event $Event -FieldName "ObjectValueName"
if ($val) { $details.Message += " | Value: $val" }
}
4698 {
$taskName = Get-EventField -Event $Event -FieldName "TaskName"
if ($taskName) { $details.Message += " | Task: $taskName" }
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
}
4648 {
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
$target = Get-EventField -Event $Event -FieldName "TargetServerName"
if ($target) { $details.Message += " | Target: $target" }
}
4769 {
$details.User = Get-EventField -Event $Event -FieldName "TargetUserName"
$encType = Get-EventField -Event $Event -FieldName "TicketEncryptionType"
$svcName = Get-EventField -Event $Event -FieldName "ServiceName"
if ($encType) { $details.Message += " | EncType: $encType" }
if ($svcName) { $details.Message += " | Service: $svcName" }
}
4771 {
$details.User = Get-EventField -Event $Event -FieldName "TargetUserName"
$details.IPAddress = Get-EventField -Event $Event -FieldName "IpAddress"
}
default {
$details.User = Get-EventField -Event $Event -FieldName "SubjectUserName"
if (-not $details.User -or $details.User -eq "N/A") {
$details.User = Get-EventField -Event $Event -FieldName "TargetUserName"
}
if (-not $details.User -or $details.User -eq "N/A") {
$sid = Get-EventField -Event $Event -FieldName "SubjectUserSid"
if ($sid) { $details.User = Get-UserFromSID -SID $sid }
}
}
}
}
catch {
Write-Log "Error extracting details for Event $($Event.Id): $($_.Exception.Message)" "WARNING"
}
return $details
}
function Get-SecurityEvents {
param([datetime]$Since)
$events = New-EventList
try {
$allIDs = @()
foreach ($cat in $Script:Config.EventIDs.Values) {
if ($cat -is [Array]) { $allIDs += $cat } else { $allIDs += $cat }
}
$allIDs = $allIDs | Sort-Object -Unique
$fileIDs = @(4660, 4661, 4663, 4656, 4658, 4699, 4654, 4670)
$registryIDs = @(4657)
$otherIDs = $allIDs | Where-Object { $_ -notin ($fileIDs + $registryIDs) }
# File events — filter 4663 to only destructive actions
$raw = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = $fileIDs; StartTime = $Since } -ErrorAction SilentlyContinue
foreach ($evt in $raw) {
$d = Get-EventDetails -Event $evt
if ($d.EventID -eq 4663) {
if ($d.Message -match "DELETE|WriteData|ChangePermissions") { $events.Add($d) }
}
else { $events.Add($d) }
}
# Registry events
$raw = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = $registryIDs; StartTime = $Since } -ErrorAction SilentlyContinue
foreach ($evt in $raw) { $events.Add((Get-EventDetails -Event $evt)) }
# All other security events
if ($otherIDs.Count -gt 0) {
$raw = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = $otherIDs; StartTime = $Since } -ErrorAction SilentlyContinue
foreach ($evt in $raw) { $events.Add((Get-EventDetails -Event $evt)) }
}
}
catch {
Write-Log "Error retrieving Security events: $($_.Exception.Message)" "ERROR"
}
return $events
}
function Get-SysmonEvents {
param([datetime]$Since)
$events = New-EventList
if (-not $Script:HasSysmon) { return $events }
try {
$sysIDs = $Script:Config.SysmonEventIDs
if (-not $sysIDs -or $sysIDs.Count -eq 0) { $sysIDs = @(1, 3, 5, 7, 8, 10, 11, 12, 13, 22, 23, 25) }
$raw = Get-WinEvent -FilterHashtable @{
LogName = $Script:SysmonLogName; ID = $sysIDs; StartTime = $Since
} -ErrorAction SilentlyContinue
foreach ($evt in $raw) {
$d = @{
Time = $evt.TimeCreated; EventID = $evt.Id; Level = $evt.LevelDisplayName
Source = "Sysmon"; Machine = $evt.MachineName; Message = $evt.Message
User = "N/A"; IPAddress = "N/A"; ProcessName = "N/A"; FilePath = "N/A"
RecordId = $evt.RecordId; Reasons = @()
}
try {
$xml = [xml]$evt.ToXml()
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event")
switch ($evt.Id) {
1 {
# Process Create
$img = $xml.SelectSingleNode("//ns:Data[@Name='Image']", $ns)
$cmd = $xml.SelectSingleNode("//ns:Data[@Name='CommandLine']", $ns)
$parent = $xml.SelectSingleNode("//ns:Data[@Name='ParentImage']", $ns)
$usr = $xml.SelectSingleNode("//ns:Data[@Name='User']", $ns)
$hash = $xml.SelectSingleNode("//ns:Data[@Name='Hashes']", $ns)
if ($img) { $d.ProcessName = $img.InnerText; $d.FilePath = $img.InnerText }
if ($cmd) { $d.Message = "Command: $($cmd.InnerText)" }
if ($parent) { $d.Message += " | Parent: $($parent.InnerText)" }
if ($usr) { $d.User = $usr.InnerText }
if ($hash) { $d.Message += " | Hash: $($hash.InnerText)" }
}
3 {
# Network Connection
$img = $xml.SelectSingleNode("//ns:Data[@Name='Image']", $ns)
$dstIP = $xml.SelectSingleNode("//ns:Data[@Name='DestinationIp']", $ns)
$dstPort = $xml.SelectSingleNode("//ns:Data[@Name='DestinationPort']", $ns)
$usr = $xml.SelectSingleNode("//ns:Data[@Name='User']", $ns)
if ($img) { $d.ProcessName = $img.InnerText }
if ($dstIP) { $d.IPAddress = $dstIP.InnerText }
if ($dstPort) { $d.Message = "Connection to $($dstIP.InnerText):$($dstPort.InnerText)" }
if ($usr) { $d.User = $usr.InnerText }
}
{ $_ -in @(8, 10) } {
# CreateRemoteThread / ProcessAccess
$src = $xml.SelectSingleNode("//ns:Data[@Name='SourceImage']", $ns)
$tgt = $xml.SelectSingleNode("//ns:Data[@Name='TargetImage']", $ns)
if ($src) { $d.ProcessName = $src.InnerText }
if ($tgt) { $d.Message = "Target: $($tgt.InnerText)" }
}
{ $_ -in @(11, 15, 23) } {
# FileCreate / FileCreateStreamHash / FileDelete
$img = $xml.SelectSingleNode("//ns:Data[@Name='Image']", $ns)
$tgtFn = $xml.SelectSingleNode("//ns:Data[@Name='TargetFilename']", $ns)
if ($img) { $d.ProcessName = $img.InnerText }
if ($tgtFn) { $d.FilePath = $tgtFn.InnerText }
}
{ $_ -in @(12, 13) } {
# Registry events
$img = $xml.SelectSingleNode("//ns:Data[@Name='Image']", $ns)
$tgtObj = $xml.SelectSingleNode("//ns:Data[@Name='TargetObject']", $ns)
if ($img) { $d.ProcessName = $img.InnerText }
if ($tgtObj) { $d.FilePath = $tgtObj.InnerText }
}
22 {
# DNS Query
$img = $xml.SelectSingleNode("//ns:Data[@Name='Image']", $ns)
$query = $xml.SelectSingleNode("//ns:Data[@Name='QueryName']", $ns)
if ($img) { $d.ProcessName = $img.InnerText }
if ($query) { $d.Message = "DNS: $($query.InnerText)"; $d.FilePath = $query.InnerText }
}
{ $_ -in @(19, 20, 21) } {
# WMI Activity
$operation = $xml.SelectSingleNode("//ns:Data[@Name='Operation']", $ns)
$user = $xml.SelectSingleNode("//ns:Data[@Name='User']", $ns)
$flt = $xml.SelectSingleNode("//ns:Data[@Name='Name']", $ns)
if ($operation) { $d.Message = "WMI $($operation.InnerText) | " }
if ($flt) {
$d.Message += "Filter/Consumer: $($flt.InnerText)"
$d.FilePath = $flt.InnerText
}
if ($user) { $d.User = $user.InnerText }
$d.Source = "Sysmon-WMI"
}
}
}
catch {}
$events.Add($d)
}
}
catch {
Write-Log "Sysmon query failed (non-fatal): $($_.Exception.Message)" "WARNING"
}
return $events
}
function Get-ADEvents {
param([datetime]$Since)
$events = New-EventList
if (-not $Script:IsDomainController) { return $events }
try {
$adIDs = $Script:Config.EventIDs.AD
if (-not $adIDs -or $adIDs.Count -eq 0) { return $events }
# Directory Service Changes log
$raw = Get-WinEvent -FilterHashtable @{
LogName = "Security"; ID = $adIDs; StartTime = $Since
} -ErrorAction SilentlyContinue
foreach ($evt in $raw) { $events.Add((Get-EventDetails -Event $evt)) }
# DS replication events (DCShadow / DCSync detection)
$dsRepIDs = @(4928, 4929, 4930, 4931, 4932, 4933, 4934, 4935, 4936)
$raw2 = Get-WinEvent -FilterHashtable @{
LogName = "Security"; ID = $dsRepIDs; StartTime = $Since
} -ErrorAction SilentlyContinue
foreach ($evt in $raw2) { $events.Add((Get-EventDetails -Event $evt)) }
}
catch {
Write-Log "AD event query failed (non-fatal): $($_.Exception.Message)" "WARNING"
}
return $events
}
function Check-WMIPersistence {
param([datetime]$Since)
$events = New-EventList
try {
$whitelist = $Script:Config.WMIWhitelist
if (-not $whitelist) { $whitelist = @("SCM Event Log Filter", "SCM Event Log Consumer", "BVTFilter") }
$filters = Get-WmiObject -Namespace "root\subscription" -Class __EventFilter -ErrorAction SilentlyContinue
foreach ($f in $filters) {
$isWhitelisted = $false
foreach ($w in $whitelist) { if ($f.Name -match $w) { $isWhitelisted = $true; break } }
if (-not $isWhitelisted) {
$events.Add(@{
Time = Get-Date; EventID = "WMI-Filter"; Level = "Critical"
Source = "WMI Persistence"; Machine = $env:COMPUTERNAME
Message = "Suspicious WMI EventFilter: $($f.Name) | Query: $($f.Query)"
User = "N/A"; IPAddress = "N/A"; ProcessName = "WMI"
FilePath = $f.Name; RecordId = "WMI-$($f.Name)"; Reasons = @("WMI persistence detected")
})
}
}
$consumers = Get-WmiObject -Namespace "root\subscription" -Class CommandLineEventConsumer -ErrorAction SilentlyContinue
foreach ($c in $consumers) {
$isWhitelisted = $false
foreach ($w in $whitelist) { if ($c.Name -match $w) { $isWhitelisted = $true; break } }
if (-not $isWhitelisted) {
$events.Add(@{
Time = Get-Date; EventID = "WMI-Consumer"; Level = "Critical"
Source = "WMI Persistence"; Machine = $env:COMPUTERNAME
Message = "Suspicious CommandLineConsumer: $($c.Name) | Cmd: $($c.CommandLineTemplate)"
User = "N/A"; IPAddress = "N/A"; ProcessName = "WMI"
FilePath = $c.Name; RecordId = "WMI-$($c.Name)"; Reasons = @("WMI consumer persistence")
})
}
}
$bindings = Get-WmiObject -Namespace "root\subscription" -Class __FilterToConsumerBinding -ErrorAction SilentlyContinue
foreach ($b in $bindings) {
$isWhitelisted = $false
foreach ($w in $whitelist) { if ($b.Filter -match $w) { $isWhitelisted = $true; break } }
if (-not $isWhitelisted) {
$events.Add(@{
Time = Get-Date; EventID = "WMI-Binding"; Level = "Critical"
Source = "WMI Persistence"; Machine = $env:COMPUTERNAME
Message = "Suspicious WMI Binding: Filter=$($b.Filter) Consumer=$($b.Consumer)"
User = "N/A"; IPAddress = "N/A"; ProcessName = "WMI"
FilePath = "Binding"; RecordId = "WMI-Bind-$($b.Filter.GetHashCode())"; Reasons = @("WMI binding persistence")
})
}
}
}
catch {
Write-Log "WMI persistence check failed (non-fatal): $($_.Exception.Message)" "WARNING"
}
return $events
}
function Get-TaskSchedulerEvents {
param([datetime]$Since)
$events = New-EventList
try {
$taskIDs = $Script:Config.EventIDs.ScheduledTaskOperational
if (-not $taskIDs) { $taskIDs = @(106, 140, 141, 200, 201) }
$raw = Get-WinEvent -FilterHashtable @{
LogName = "Microsoft-Windows-TaskScheduler/Operational"; ID = $taskIDs; StartTime = $Since
} -ErrorAction SilentlyContinue
foreach ($evt in $raw) {
$d = @{
Time = $evt.TimeCreated; EventID = $evt.Id; Level = $evt.LevelDisplayName
Source = "TaskScheduler"; Machine = $evt.MachineName; Message = $evt.Message
User = "N/A"; IPAddress = "N/A"; ProcessName = "TaskScheduler"; FilePath = "N/A"
RecordId = $evt.RecordId; Reasons = @()
}
try {
$xml = [xml]$evt.ToXml()
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event")
$tn = $xml.SelectSingleNode("//ns:Data[@Name='TaskName']", $ns)
if ($tn) { $d.FilePath = $tn.InnerText; $d.Message += " | Task: $($tn.InnerText)" }
}
catch {}
if ($d.FilePath -eq "N/A" -and $evt.Message -match "Task Name:\s*([^\r\n]+)") {
$d.FilePath = $matches[1].Trim()
}
$events.Add($d)
}
}
catch {}
return $events
}
function Get-ServiceEvents {
param([datetime]$Since)
$events = New-EventList
try {
$svcIDs = @(7034, 7035, 7036, 7040, 7045)
$raw = Get-WinEvent -FilterHashtable @{LogName = "System"; ID = $svcIDs; StartTime = $Since } -ErrorAction SilentlyContinue
foreach ($evt in $raw) {
$d = @{
Time = $evt.TimeCreated; EventID = $evt.Id; Level = $evt.LevelDisplayName
Source = "Service Control Manager"; Machine = $evt.MachineName; Message = $evt.Message
User = "N/A"; IPAddress = "N/A"; ProcessName = "Services"; FilePath = "N/A"
RecordId = $evt.RecordId; Reasons = @()
}
try {
$xml = [xml]$evt.ToXml()
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event")
$p1 = $xml.SelectSingleNode("//ns:Data[@Name='param1']", $ns)
if ($p1) { $d.FilePath = $p1.InnerText; $d.Message += " | Service: $($p1.InnerText)" }
}
catch {}
$events.Add($d)
}
# Security log service install (4697)
$raw2 = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = 4697; StartTime = $Since } -ErrorAction SilentlyContinue
foreach ($evt in $raw2) { $events.Add((Get-EventDetails -Event $evt)) }
}
catch {}
return $events
}
function Get-PowerShellEvents {
param([datetime]$Since)
$events = New-EventList
$selfName = "SecurityMonitor"
try {
$psIDs = $Script:Config.EventIDs.PowerShell
if (-not $psIDs) { $psIDs = @(4103, 4104, 4105, 4106) }
$raw = Get-WinEvent -FilterHashtable @{
LogName = "Microsoft-Windows-PowerShell/Operational"; ID = $psIDs; StartTime = $Since
} -ErrorAction SilentlyContinue
foreach ($evt in $raw) {
$msg = $evt.Message
# Skip self-generated events
if ($msg -match [regex]::Escape($selfName)) { continue }
if ($evt.Id -eq 4104) {
if ($msg -match "Creating Scriptblock text \(1 of 1\):\s*([^\r\n]+)") {
$cmd = $matches[1].Trim()
if ($cmd -match "^\s*prompt\s*$|^\s*cd\s+\S+\s*$|^\s*\$Host\s*$|Get-Location\s*$|Get-Command\s*$|Get-Help\s*$|^\s*dir\s*$|^\s*ls\s*$|^\s*pwd\s*$|^\s*clear\s*$|Set-StrictMode|ErrorCategory_Message|PSMessageDetails") {
continue
}
}
}
if ($evt.Id -in @(4105, 4106)) {
if ($msg -match "prompt|Runspace|ScriptBlock ID|Completed invocation|Started invocation") { continue }
}
$userId = "N/A"
try {
$xml = [xml]$evt.ToXml()
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event")
$userSid = $xml.SelectSingleNode("//ns:UserId", $ns)
if ($userSid) { $userId = Get-UserFromSID -SID $userSid.InnerText }
}
catch {}
if ($userId -eq "N/A") { $userId = $env:USERNAME }
$events.Add(@{
Time = $evt.TimeCreated; EventID = $evt.Id; Level = "Warning"
Source = "PowerShell"; Machine = $evt.MachineName; Message = $msg
User = $userId; IPAddress = "N/A"; ProcessName = "PowerShell"; FilePath = "N/A"
RecordId = $evt.RecordId; Reasons = @()
})
}
}
catch {}
return $events
}
function Test-NoiseFilter {
param([hashtable]$Event)
if ($Event.User -in $Script:Config.NoiseFilters.Users) {
foreach ($np in $Script:Config.NoiseFilters.Paths) {
if ($Event.FilePath -match $np -or $Event.Message -match $np) { return $true }
}
}
return $false
}
function Test-SuspiciousActivity {
param([hashtable]$Event)
$isSuspicious = $false
$reasons = [System.Collections.Generic.List[string]]::new()
# Suspicious process
if ($Event.ProcessName) {
$procBase = Split-Path -Leaf $Event.ProcessName -ErrorAction SilentlyContinue
if ($procBase -and $procBase -in $Script:Config.SuspiciousProcesses) {
$isSuspicious = $true; $reasons.Add("Suspicious process: $procBase")
}
}
# Suspicious file type
if ($Event.FilePath -match "\.(exe|dll|bat|cmd|ps1|vbs|js|jar|hta|scr)$") {
$isSuspicious = $true; $reasons.Add("Suspicious file type: $($Event.FilePath)")
}
# Failed logon
if ($Event.EventID -eq 4625) { $isSuspicious = $true; $reasons.Add("Failed logon attempt") }
# Admin activity (not PS noise)
if ($Event.User -match "Administrator|Admin" -and $Event.EventID -notin @(4104, 4105, 4106)) {
if ($Event.EventID -in @(4624, 4648, 4672, 4720, 4722, 4724, 4726, 4728, 4732, 4733, 4756)) {
$isSuspicious = $true; $reasons.Add("Administrator account activity")
}
}
# External IP — fixed to exclude localhost/loopback
if ($Event.IPAddress -and $Event.IPAddress -ne "N/A" -and $Event.IPAddress -ne "-" -and
$Event.IPAddress -ne "127.0.0.1" -and $Event.IPAddress -ne "::1" -and
$Event.IPAddress -notmatch "^192\.168\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.") {
$isSuspicious = $true; $reasons.Add("External IP: $($Event.IPAddress)")
}
# Account modification
if ($Event.EventID -in $Script:Config.EventIDs.Account) {
$isSuspicious = $true; $reasons.Add("Account modification detected")
}
# PowerShell attack patterns
if ($Event.EventID -in @(4104, 4105, 4106)) {
if ($Event.Message -match "Invoke-Expression|IEX|DownloadString|WebClient|Net\.WebClient|Start-Process.*-WindowStyle.*Hidden|Invoke-WebRequest.*-UseBasicParsing|base64.*encoded|bypass.*execution|obfuscated|Invoke-Mimikatz|Invoke-Kerberoast|Invoke-BloodHound|Invoke-SMBExec|Invoke-WMIExec|Invoke-DCSync|SharpHound|Rubeus") {
$isSuspicious = $true; $reasons.Add("Suspicious PowerShell command")
}
}
# Kerberoasting: TGS request with RC4 encryption
if ($Event.EventID -eq 4769 -and $Event.Message -match "EncType:\s*0x17") {
$isSuspicious = $true; $reasons.Add("Possible Kerberoasting (RC4 TGS request)")
}
# AS-REP Roasting
if ($Event.EventID -eq 4768 -and $Event.Message -match "EncType:\s*0x17") {
$isSuspicious = $true; $reasons.Add("Possible AS-REP roasting (RC4 TGT)")
}
# Pre-auth failure
if ($Event.EventID -eq 4771) { $isSuspicious = $true; $reasons.Add("Kerberos pre-auth failure") }
# Sysmon: CreateRemoteThread (injection)
if ($Event.Source -eq "Sysmon" -and $Event.EventID -eq 8) {
$isSuspicious = $true; $reasons.Add("Remote thread injection (Sysmon)")
}
# Sysmon: Process Access (credential dumping — lsass)
if ($Event.Source -eq "Sysmon" -and $Event.EventID -eq 10) {
if ($Event.Message -match "lsass\.exe") {
$isSuspicious = $true; $reasons.Add("LSASS access detected (credential dumping?)")
}
}
# WMI persistence
if ($Event.Source -match "WMI Persistence|WMI-Activity|Sysmon-WMI") {
$isSuspicious = $true
$reasons.Add("WMI persistence activity detected: $($Event.Source)")
}
# AD replication events (DCSync)
if ($Event.EventID -in @(4928, 4929, 4662)) {
if ($Event.Message -match "Replicating Directory Changes|DS-Replication-Get-Changes") {
$isSuspicious = $true; $reasons.Add("Possible DCSync attack")
}
}
return @{ IsSuspicious = $isSuspicious; Reasons = $reasons }
}
function Remove-DuplicateEvents {
param([System.Collections.Generic.List[object]]$Events)
$unique = New-EventList
$seen = @{}
foreach ($evt in $Events) {
$key = "$($evt.RecordId)-$($evt.EventID)-$($evt.Time.ToString('yyyyMMddHHmmss'))"
if (-not $seen.ContainsKey($key)) { $seen[$key] = $true; $unique.Add($evt) }
}
return $unique
}
function Detect-BruteForce {
param([System.Collections.Generic.List[object]]$Events)
$threshold = $Script:Config.BruteForceThreshold
if (-not $threshold) { $threshold = 5 }
$failedLogons = $Events | Where-Object { $_.EventID -eq 4625 }
if ($failedLogons.Count -lt $threshold) { return }
# Group by source IP
$byIP = @{}
foreach ($evt in $failedLogons) {
$ip = if ($evt.IPAddress -and $evt.IPAddress -ne "N/A") { $evt.IPAddress } else { "Unknown" }
if (-not $byIP.ContainsKey($ip)) { $byIP[$ip] = 0 }
$byIP[$ip]++
}
foreach ($ip in $byIP.Keys) {
if ($byIP[$ip] -ge $threshold) {
Write-Log "BRUTE FORCE: $($byIP[$ip]) failed logons from $ip in last check window!" "CRITICAL"
$alert = @{
Time = Get-Date; EventID = "BruteForce"; Level = "Critical"
Source = "BruteForce Detection"; Machine = $env:COMPUTERNAME
Message = "$($byIP[$ip]) failed logon attempts from IP: $ip"
User = "Multiple"; IPAddress = $ip; ProcessName = "N/A"; FilePath = "N/A"
RecordId = "BF-$ip"; Reasons = @("Brute force: $($byIP[$ip]) attempts from $ip")
}
Show-Alert -Events @($alert) -AlertType "BRUTE FORCE ATTACK DETECTED"
}
}
# Group by target user
$byUser = @{}
foreach ($evt in $failedLogons) {
$user = if ($evt.User -and $evt.User -ne "N/A") { $evt.User } else { "Unknown" }
if (-not $byUser.ContainsKey($user)) { $byUser[$user] = 0 }
$byUser[$user]++
}
foreach ($user in $byUser.Keys) {
if ($byUser[$user] -ge $threshold -and $user -ne "Unknown") {
Write-Log "BRUTE FORCE: $($byUser[$user]) failed logons targeting user '$user'!" "CRITICAL"
}
}
}
function Write-AlertToLog {
param([array]$Events, [string]$AlertType = "Security Event")
if (-not $Script:LogFilePath -or [string]::IsNullOrWhiteSpace($Script:LogFilePath)) { return }
try {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "`n" + ("=" * 100)
$logEntry += "`n$AlertType - $($Events.Count) Event(s) - $timestamp"
$logEntry += "`nSystem: $($Script:Config.SystemName) | Domain: $($Script:Config.Domain)"
$logEntry += "`n" + ("-" * 100)
foreach ($evt in $Events) {
$logEntry += "`nEvent ID: $($evt.EventID) | Level: $($evt.Level) | Time: $($evt.Time.ToString('yyyy-MM-dd HH:mm:ss'))"
$logEntry += "`nUser: $($evt.User)"
if ($evt.IPAddress -ne "N/A") { $logEntry += " | IP: $($evt.IPAddress)" }
if ($evt.ProcessName -ne "N/A") { $logEntry += "`nProcess: $($evt.ProcessName)" }
if ($evt.FilePath -ne "N/A" -and $evt.FilePath -ne $evt.ProcessName) { $logEntry += "`nPath: $($evt.FilePath)" }
if ($evt.Reasons -and $evt.Reasons.Count -gt 0) { $logEntry += "`nFlags: $($evt.Reasons -join ', ')" }
$msgLines = ($evt.Message -split "`n" | Select-Object -First 3) -join " | "
$logEntry += "`nDetails: $msgLines"
$logEntry += "`n" + ("-" * 100)
}
$logEntry += "`n" + ("=" * 100)
Add-Content -Path $Script:LogFilePath -Value $logEntry -ErrorAction SilentlyContinue