-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefender_code.ps1
More file actions
1458 lines (1238 loc) · 61.2 KB
/
Copy pathdefender_code.ps1
File metadata and controls
1458 lines (1238 loc) · 61.2 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
# ==============================================================================
# BLUE TEAM DEFENDER - Integrated Security Scanner v5.0 (COMPLETE)
# ==============================================================================
# Full working script - Copy all parts sequentially
# Save as: BlueTeam_Defender_v5.0.ps1
# Run as Administrator for full functionality
# ==============================================================================
#Requires -Version 5.0
$ErrorActionPreference = 'SilentlyContinue'
# ==============================================================================
# CONFIGURATION
# ==============================================================================
$Config = @{
# Core IOCs
RegRunPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
RegRunName = "WinUpdateSvc"
TaskName = "MicrosoftUpdateHelper"
PwnedFile = "C:\Users\Public\Documents\pwned.txt"
# Ghost persistence detection
GhostRegPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
GhostRegName = "BlueTeamDefenderGuard"
# GUID drop folder IOCs
GuidFolderName = '{B6341000-21CD-4C19-82CF-60C4C444FDC7}'
GuidDropFolder = "$env:TEMP\{B6341000-21CD-4C19-82CF-60C4C444FDC7}"
EncodedFileName = 'powershell script to base64 UTF16-LE string.ps1'
# Hunt strings
HuntStrings = @("pwned.txt", "pwned", "Pwn3d", "WinUpdateSvc",
"MicrosoftUpdateHelper", "B6341000-21CD-4C19-82CF-60C4C444FDC7",
"powershell script to base64 UTF16-LE string", "SystemUIHost", "SystemUIHostTask")
# Suspect script filenames
SuspectScripts = @(
"svchost_helper.ps1", "svchost_helper_bak.ps1", "WinDefSvc.ps1",
"WindowsUpdateService.ps1", "WindowsUpdateService_integrated.ps1",
"powershell script to base64 UTF16-LE string.ps1", "final_attack.ps1"
)
# PS1 extensions to hunt
SuspiciousExtensions = @('.ps1','.vbs','.js','.wsf','.hta','.bat','.cmd','.py','.rb','.jar','.jse','.wsh')
# Suspicious paths
SuspiciousPaths = @(
'\AppData\', '\Temp\', '\tmp\', '\Public\', '\ProgramData\',
'\Downloads\', '\Desktop\', '\Users\', '\Documents\', '\Music\',
'\Pictures\', '\Videos\', '\Recycle', 'C:\Windows\Temp'
)
# Argument red flags
ArgumentRedFlags = @(
'-bypass', '-encodedcommand', '-enc ', '-windowstyle hidden',
'-w hidden', '-nop ', '-noprofile', 'frombase64', 'iex ',
'invoke-expression', 'downloadstring', 'webclient',
'hidden.*bypass', 'executionpolicy bypass', '-Win Hidden'
)
# Interpreter patterns
InterpreterPatterns = @(
'powershell', 'pwsh', 'wscript', 'cscript', 'mshta', 'wmic',
'msiexec', 'regsvr32', 'rundll32', 'certutil', 'bitsadmin', 'cmd\.exe\s.*/[cCkK]'
)
# Filesystem roots to scan
SearchRoots = @(
$env:TEMP, $env:APPDATA, $env:LOCALAPPDATA,
"C:\Users\Public", "C:\Windows\Temp", "C:\ProgramData",
"C:\Windows\System32\Tasks", "$env:USERPROFILE\Downloads",
"$env:USERPROFILE\Desktop", "$env:USERPROFILE\Documents"
)
# Registry hives to deep-scan
RegHivesToScan = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnceEx",
"HKCU:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnceEx",
"HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon",
"HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon",
"HKLM:\System\CurrentControlSet\Control\Lsa",
"HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Windows",
"HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options",
"HKLM:\System\CurrentControlSet\Services",
"HKCU:\Environment"
)
# Startup folders
StartupFolders = @(
[Environment]::GetFolderPath('Startup'),
[Environment]::GetFolderPath('CommonStartup'),
"$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup",
"$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Startup",
'C:\Windows\Start Menu\Programs\Startup'
) | Sort-Object -Unique
# Watchdog timing
WatchdogIntervalSeconds = 30
# Output paths
ReportPath = "$env:USERPROFILE\Desktop\BlueTeam_Defender_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
WatchdogResultsPath = "$env:USERPROFILE\Desktop\BlueTeam_Watchdog_Results_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
WatchdogLogPath = "$env:USERPROFILE\Desktop\BlueTeam_Defender_Watchdog.txt"
DesktopShortcutPath = "$env:USERPROFILE\Desktop\BlueTeam_Defender_Watchdog.lnk"
}
# ==============================================================================
# GLOBAL STATE
# ==============================================================================
$script:Findings = [System.Collections.Generic.List[PSCustomObject]]::new()
$script:WatchdogFindings = [System.Collections.Generic.List[PSCustomObject]]::new()
$script:Removed = 0
$script:Skipped = 0
$script:CycleCount = 0
$script:TotalRemoved = 0
$script:WatchdogRunning = $true
$script:StartTime = Get-Date
# ==============================================================================
# UTILITY FUNCTIONS
# ==============================================================================
function Write-Banner {
param([string]$Text, [string]$Color = "Cyan")
$line = "=" * 70
Write-Host "`n$line" -ForegroundColor $Color
Write-Host " $Text" -ForegroundColor $Color
Write-Host "$line" -ForegroundColor $Color
}
function Write-Section {
param([string]$T)
Write-Host "`n$("=" * 70)`n $T`n$("=" * 70)" -ForegroundColor Cyan
}
function Write-Sub {
param([string]$T)
Write-Host "`n -- $T" -ForegroundColor DarkCyan
}
function Write-OK {
param([string]$m)
Write-Host " [OK] $m" -ForegroundColor Green
}
function Write-Info {
param([string]$m)
Write-Host " [INFO] $m" -ForegroundColor Gray
}
function Write-Finding {
param(
[string]$Category,
[string]$Name,
[string]$Detail,
[string]$Reason,
[string]$Action = 'Removed',
[switch]$WatchdogMode
)
$finding = [PSCustomObject]@{
Category = $Category
Name = $Name
Detail = $Detail
Reason = $Reason
Action = $Action
Time = Get-Date
Cycle = if ($WatchdogMode) { $script:CycleCount } else { 0 }
Type = if ($WatchdogMode) { "WATCHDOG" } else { "INITIAL_SCAN" }
}
if ($WatchdogMode) {
$script:WatchdogFindings.Add($finding)
} else {
$script:Findings.Add($finding)
}
# Console output
$prefix = if ($WatchdogMode) { " [WATCH][FOUND]" } else { " [FOUND]" }
Write-Host "$prefix $Category : $Name" -ForegroundColor Red
Write-Host " $Detail" -ForegroundColor DarkYellow
Write-Host " Reason : $Reason" -ForegroundColor DarkYellow
# Immediately save to appropriate report file
$reportLine = @"
[$([DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss'))] [$($finding.Type)] CATEGORY: $Category
Name: $Name
Detail: $Detail
Reason: $Reason
Action: $Action
$(if ($WatchdogMode) { " Cycle: $($script:CycleCount)`n" } else { "`n" })
"@
if ($WatchdogMode) {
$reportLine | Out-File -FilePath $Config.WatchdogResultsPath -Append -Encoding UTF8 -ErrorAction SilentlyContinue
$reportLine | Out-File -FilePath $Config.ReportPath -Append -Encoding UTF8 -ErrorAction SilentlyContinue
} else {
$reportLine | Out-File -FilePath $Config.ReportPath -Append -Encoding UTF8 -ErrorAction SilentlyContinue
}
}
function Write-Removed {
param([string]$m, [switch]$WatchdogMode)
$prefix = if ($WatchdogMode) { " [W-REMOVED]" } else { " [REMOVED]" }
Write-Host "$prefix $m" -ForegroundColor Green
$script:Removed++
$script:TotalRemoved++
$removalLine = "[$([DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss'))] REMOVED: $m`n"
$removalLine | Out-File -FilePath $Config.ReportPath -Append -Encoding UTF8 -ErrorAction SilentlyContinue
if ($WatchdogMode) {
$removalLine | Out-File -FilePath $Config.WatchdogResultsPath -Append -Encoding UTF8 -ErrorAction SilentlyContinue
}
}
function Write-WatchStatus {
param([string]$Label, [string]$Status, [string]$Color = "Green")
Write-Host (" {0,-50} {1}" -f $Label, $Status) -ForegroundColor $Color
}
function Confirm-Auto {
param([string]$Prompt)
Write-Host " [AUTO-YES] $Prompt" -ForegroundColor DarkGray
return $true
}
function Test-IsSuspicious {
param(
[string]$CommandLine = '',
[string]$Name = '',
[string]$ExtraContext = ''
)
$haystack = ($CommandLine + ' ' + $Name + ' ' + $ExtraContext).ToLower()
foreach ($kw in $Config.HuntStrings) {
if ($haystack -like "*$($kw.ToLower())*") {
return $true, "Contains hunt keyword '$kw'"
}
}
foreach ($path in $Config.SuspiciousPaths) {
if ($haystack -like "*$($path.ToLower())*") {
return $true, "Binary/script located in user-writable path: $path"
}
}
foreach ($flag in $Config.ArgumentRedFlags) {
if ($haystack -match [regex]::Escape($flag.ToLower()) -or $haystack -match $flag.ToLower()) {
return $true, "Suspicious argument flag: $flag"
}
}
foreach ($ext in $Config.SuspiciousExtensions) {
if ($haystack -like "*$ext*") {
return $true, "Persistence entry invokes script file (*$ext)"
}
}
foreach ($pat in $Config.InterpreterPatterns) {
if ($haystack -match $pat) {
$isSystemBinary = ($CommandLine -match '(?i)C:\\Windows\\System32\\' -or
$CommandLine -match '(?i)C:\\Windows\\SysWOW64\\') -and
($CommandLine -notmatch '(?i)(appdata|temp|public|programdata|downloads|users)')
if (-not $isSystemBinary) {
return $true, "Interpreter-based launcher outside System32: $pat"
}
}
}
return $false, ''
}
function Test-FileIsDropper {
param([string]$FilePath)
if (-not (Test-Path $FilePath -PathType Leaf)) { return $false }
try {
$ext = [System.IO.Path]::GetExtension($FilePath).ToLower()
if ($ext -notin @('.ps1','.vbs','.bat','.cmd','.js','.wsf','.hta','.txt','.py','.rb','.sh','.ini','.cfg','.xml')) {
return $false
}
$content = Get-Content -Path $FilePath -Raw -ErrorAction Stop
foreach ($kw in $Config.HuntStrings) {
if ($content -match [regex]::Escape($kw)) { return $true }
}
} catch {}
return $false
}
function Remove-PersistenceEntry {
param(
[scriptblock]$RemoveBlock,
[string]$Label,
[switch]$WatchdogMode
)
try {
& $RemoveBlock
Write-Removed "$Label" -WatchdogMode:$WatchdogMode
return $true
} catch {
$script:Skipped++
Write-Host " [FAILED] $Label - $_" -ForegroundColor Magenta
return $false
}
}
function Get-DecodedPayload {
param([string]$FilePath)
try {
$raw = Get-Content $FilePath -Raw -Encoding UTF8 -EA Stop
$match = [regex]::Match($raw, '[A-Za-z0-9+/]{100,}={0,2}')
if (-not $match.Success) { return $null }
$bytes = [Convert]::FromBase64String($match.Value)
$decoded = [System.Text.Encoding]::Unicode.GetString($bytes)
return $decoded
} catch { return $null }
}
# ==============================================================================
# DEFENSIVE REGISTRY ENTRY
# ==============================================================================
function Install-DefensiveRegistryGuard {
Write-Banner "DEFENSIVE MEASURE - Ghost Registry Guard"
$defenderScript = @"
# BlueTeam Defender Guard - Auto-cleans ghost persistence
`$ErrorActionPreference = 'SilentlyContinue'
Start-Sleep -Seconds 3
Get-Process -Name "powershell","pwsh" -EA SilentlyContinue | ForEach-Object {
try {
`$cmd = (Get-CimInstance Win32_Process -Filter "ProcessId=`$(`$_.Id)" -EA Stop).CommandLine
if (`$cmd -match "pwned|Pwn3d|Set-Content.*pwned") {
Stop-Process -Id `$_.Id -Force -EA SilentlyContinue
}
} catch {}
}
if (Test-Path "C:\Users\Public\Documents\pwned.txt") {
Remove-Item "C:\Users\Public\Documents\pwned.txt" -Force -EA SilentlyContinue
}
`$runPaths = @(
'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run'
)
foreach (`$rp in `$runPaths) {
if (Test-Path `$rp) {
Get-ItemProperty -Path `$rp -EA SilentlyContinue | ForEach-Object {
`$_.PSObject.Properties | Where-Object {
`$_.Name -notmatch '^PS' -and `$_.Value -match 'powershell.*pwned'
} | ForEach-Object {
Remove-ItemProperty -Path `$rp -Name `$_.Name -Force -EA SilentlyContinue
}
}
}
}
"@
$guardScriptPath = "$env:TEMP\BlueTeamGuard.ps1"
$defenderScript | Out-File -FilePath $guardScriptPath -Encoding ASCII -Force
$guardCommand = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$guardScriptPath`""
try {
Set-ItemProperty -Path $Config.GhostRegPath -Name $Config.GhostRegName -Value $guardCommand -Force
Write-OK "Defensive registry guard installed at: $($Config.GhostRegPath)\$($Config.GhostRegName)"
} catch {
Write-Info "Could not install defensive guard: $_"
}
}
# ==============================================================================
# MODULE 1 - Registry Run/RunOnce Keys
# ==============================================================================
function Invoke-ScanRegistryRunKeys {
Write-Banner "MODULE 1 - Registry Run / RunOnce Keys (PS1 Hunter)"
$runPaths = @(
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce',
'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnceEx',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce',
'HKCU:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\Environment'
)
foreach ($regPath in $runPaths) {
if (-not (Test-Path $regPath)) { continue }
$item = Get-Item -Path $regPath -ErrorAction SilentlyContinue
if (-not $item) { continue }
$values = if ($regPath -like '*\Environment') {
$item.GetValueNames() | Where-Object { $_ -eq 'UserInitMprLogonScript' }
} else {
$item.GetValueNames() | Where-Object { $_ -ne '' }
}
foreach ($valueName in $values) {
$valueData = $item.GetValue($valueName)
$hasPS1 = $valueData -match '\.ps1'
$hasPowerShell = $valueData -match 'powershell|pwsh'
$hasPwned = $valueData -match 'pwned|Pwn3d'
$hasHidden = $valueData -match '-Win Hidden|-windowstyle hidden|-w hidden'
$suspicious, $reason = Test-IsSuspicious -CommandLine $valueData -Name $valueName
if ($hasPS1 -or ($hasPowerShell -and ($hasPwned -or $hasHidden))) {
$suspicious = $true
if ($hasPS1) { $reason = "Registry entry executes .ps1 script file" }
if ($hasPowerShell -and $hasPwned) { $reason = "PowerShell command with pwned keyword in Run key" }
if ($hasPowerShell -and $hasHidden) { $reason = "PowerShell with hidden window in Run key" }
}
if ($suspicious) {
Write-Finding -Category 'Registry Run Key' `
-Name "$regPath\$valueName" `
-Detail "Value: $valueData" `
-Reason $reason
Remove-PersistenceEntry -Label "$regPath\$valueName" -RemoveBlock {
Remove-ItemProperty -Path $regPath -Name $valueName -Force -ErrorAction Stop
}
} else {
Write-OK "$regPath\$valueName"
}
}
}
# Winlogon overrides
$winlogonPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
if (Test-Path $winlogonPath) {
foreach ($keyName in @('Userinit','Shell','UserInitMprLogonScript')) {
$val = (Get-ItemProperty -Path $winlogonPath -Name $keyName -ErrorAction SilentlyContinue).$keyName
if (-not $val) { continue }
$suspicious, $reason = Test-IsSuspicious -CommandLine $val -Name $keyName
if ($suspicious) {
Write-Finding -Category 'Winlogon Override' `
-Name "$winlogonPath\$keyName" `
-Detail "Value: $val" `
-Reason "Winlogon $keyName has suspicious entry"
$safeValue = if ($keyName -eq 'Shell') { 'explorer.exe' } else { 'C:\Windows\system32\userinit.exe,' }
Remove-PersistenceEntry -Label "Restore $keyName to default" -RemoveBlock {
Set-ItemProperty -Path $winlogonPath -Name $keyName -Value $safeValue -Force -ErrorAction Stop
}
} else {
Write-OK "Winlogon $keyName = $val"
}
}
}
}
# ==============================================================================
# MODULE 2 - Startup Folders
# ==============================================================================
function Invoke-ScanStartupFolders {
Write-Banner "MODULE 2 - Startup Folders"
foreach ($folder in $Config.StartupFolders) {
if (-not (Test-Path $folder)) { continue }
Write-Sub $folder
$items = Get-ChildItem -Path $folder -Force -ErrorAction SilentlyContinue
if (-not $items) {
Write-OK "Startup folder empty"
continue
}
foreach ($entry in $items) {
$suspicious = $false
$reason = ''
$targetPath = $entry.FullName
$ext = $entry.Extension.ToLower()
if ($ext -in $Config.SuspiciousExtensions) {
$suspicious = $true
$reason = "Script file ($ext) in Startup folder"
}
if ($ext -eq '.lnk') {
try {
$shell = New-Object -ComObject WScript.Shell
$lnk = $shell.CreateShortcut($entry.FullName)
$target = $lnk.TargetPath + ' ' + $lnk.Arguments
$suspicious, $reason = Test-IsSuspicious -CommandLine $target -Name $entry.Name
$targetPath = $target
} catch {}
}
if (-not $suspicious -and $ext -eq '.exe') {
$suspicious, $reason = Test-IsSuspicious -CommandLine $entry.FullName -Name $entry.Name
}
if (-not $suspicious -and (Test-FileIsDropper -FilePath $entry.FullName)) {
$suspicious = $true
$reason = 'File content contains payload keyword'
}
if ($suspicious) {
Write-Finding -Category 'Startup Folder' `
-Name $entry.Name `
-Detail "Path: $($entry.FullName) -> $targetPath" `
-Reason $reason
$entryPath = $entry.FullName
Remove-PersistenceEntry -Label $entry.FullName -RemoveBlock {
Remove-Item -Path $entryPath -Force -Recurse -ErrorAction Stop
}
} else {
Write-OK "Startup: $($entry.Name)"
}
}
}
}
# ==============================================================================
# MODULE 3 - Scheduled Tasks
# ==============================================================================
function Invoke-ScanScheduledTasks {
Write-Banner "MODULE 3 - Scheduled Tasks"
$safeMicrosoftPaths = @(
'\Microsoft\Windows\AppID\', '\Microsoft\Windows\Application Experience\',
'\Microsoft\Windows\Autochk\', '\Microsoft\Windows\Bluetooth\',
'\Microsoft\Windows\Diagnosis\', '\Microsoft\Windows\DiskCleanup\',
'\Microsoft\Windows\Windows Defender\', '\Microsoft\Windows\WindowsUpdate\'
)
try {
$allTasks = Get-ScheduledTask -ErrorAction SilentlyContinue
} catch {
Write-Host ' [!] Cannot enumerate scheduled tasks - try running as Administrator' -ForegroundColor Magenta
return
}
foreach ($task in $allTasks) {
$fullPath = '\' + $task.TaskPath.TrimStart('\') + $task.TaskName
$actionContext = ''
if ($task.Actions) {
foreach ($action in $task.Actions) {
if ($action.CimClass.CimClassName -eq 'MSFT_TaskExecAction') {
$actionContext += ' ' + $action.Execute + ' ' + $action.Arguments
}
if ($action.CimClass.CimClassName -eq 'MSFT_TaskComHandlerAction') {
$actionContext += ' ' + $action.ClassId + ' ' + $action.Data
}
}
}
$suspicious, $reason = Test-IsSuspicious -CommandLine $actionContext -Name $task.TaskName -ExtraContext $task.TaskPath
$isMicrosoftPath = $false
foreach ($safePath in $safeMicrosoftPaths) {
if ($task.TaskPath -like "*$safePath*" -or $task.TaskPath -eq $safePath.TrimEnd('\')) {
$isMicrosoftPath = $true; break
}
}
if ($isMicrosoftPath -and -not $suspicious) {
foreach ($pat in @('powershell','pwsh','wscript','cscript','mshta','cmd\.exe')) {
if ($actionContext -match $pat) {
$suspicious = $true
$reason = "Microsoft-namespaced task path runs interpreter ($pat) - likely masquerade"
break
}
}
}
if ($suspicious) {
Write-Finding -Category 'Scheduled Task' `
-Name $fullPath `
-Detail "Action: $($actionContext.Trim())" `
-Reason $reason
$tPath = $task.TaskPath
$tName = $task.TaskName
Remove-PersistenceEntry -Label "Task: $fullPath" -RemoveBlock {
Unregister-ScheduledTask -TaskPath $tPath -TaskName $tName -Confirm:$false -ErrorAction Stop
}
} else {
Write-OK "Task: $fullPath"
}
}
}
# ==============================================================================
# MODULE 4 - Windows Services
# ==============================================================================
function Invoke-ScanServices {
Write-Banner "MODULE 4 - Windows Services"
$services = Get-WmiObject Win32_Service -ErrorAction SilentlyContinue
if (-not $services) {
Write-Host ' [!] WMI service query failed' -ForegroundColor Magenta
return
}
foreach ($svc in $services) {
$binPath = $svc.PathName -replace '"',''
if (-not $binPath) { continue }
$suspicious, $reason = Test-IsSuspicious -CommandLine $binPath -Name $svc.Name
if ($suspicious) {
Write-Finding -Category 'Windows Service' `
-Name $svc.Name `
-Detail "Binary: $binPath | Start: $($svc.StartMode) | State: $($svc.State)" `
-Reason $reason
$svcName = $svc.Name
Remove-PersistenceEntry -Label "Service disabled+stopped: $svcName" -RemoveBlock {
Stop-Service -Name $svcName -Force -ErrorAction SilentlyContinue
Set-Service -Name $svcName -StartupType Disabled -ErrorAction Stop
}
} else {
Write-OK "Service: $($svc.Name) [$($svc.StartMode)]"
}
}
}
# ==============================================================================
# MODULE 5 - WMI Permanent Event Subscriptions
# ==============================================================================
function Invoke-ScanWMISubscriptions {
Write-Banner "MODULE 5 - WMI Permanent Event Subscriptions"
try {
$filters = Get-WMIObject -Namespace 'root\subscription' -Class '__EventFilter' -ErrorAction Stop
$consumers = Get-WMIObject -Namespace 'root\subscription' -Class '__EventConsumer' -ErrorAction Stop
$bindings = Get-WMIObject -Namespace 'root\subscription' -Class '__FilterToConsumerBinding' -ErrorAction Stop
} catch {
Write-Host ' [!] WMI namespace query failed (admin required)' -ForegroundColor Magenta
return
}
$wmiClean = $true
foreach ($filter in $filters) {
$wmiClean = $false
Write-Finding -Category 'WMI EventFilter' `
-Name $filter.Name `
-Detail "Query: $($filter.Query)" `
-Reason 'WMI EventFilter found - root\subscription should be empty on clean systems'
Remove-PersistenceEntry -Label "WMI Filter: $($filter.Name)" -RemoveBlock {
$filter | Remove-WMIObject -ErrorAction Stop
}
}
foreach ($consumer in $consumers) {
$wmiClean = $false
$detail = if ($consumer.CommandLineTemplate) { "CMD: $($consumer.CommandLineTemplate)" }
elseif ($consumer.ScriptText) { "Script: $($consumer.ScriptText.Substring(0,[math]::Min(80,$consumer.ScriptText.Length)))..." }
else { "ClassID: $($consumer.__CLASS)" }
Write-Finding -Category 'WMI EventConsumer' `
-Name $consumer.Name `
-Detail $detail `
-Reason 'WMI EventConsumer found - root\subscription should be empty on clean systems'
Remove-PersistenceEntry -Label "WMI Consumer: $($consumer.Name)" -RemoveBlock {
$consumer | Remove-WMIObject -ErrorAction Stop
}
}
foreach ($binding in $bindings) {
$wmiClean = $false
Write-Finding -Category 'WMI FilterToConsumerBinding' `
-Name "$($binding.Filter) -> $($binding.Consumer)" `
-Detail "Binding in root\subscription" `
-Reason 'WMI Binding found - root\subscription should be empty on clean systems'
Remove-PersistenceEntry -Label 'WMI Binding removed' -RemoveBlock {
$binding | Remove-WMIObject -ErrorAction Stop
}
}
if ($wmiClean) { Write-OK 'WMI root\subscription is clean' }
}
# ==============================================================================
# MODULE 6 - BITS Jobs
# ==============================================================================
function Invoke-ScanBITSJobs {
Write-Banner "MODULE 6 - BITS Transfer Jobs"
try {
$jobs = Get-BitsTransfer -AllUsers -ErrorAction Stop
} catch {
Write-Host ' [!] BITS enumeration failed (admin required for -AllUsers)' -ForegroundColor Magenta
try { $jobs = Get-BitsTransfer -ErrorAction SilentlyContinue } catch { return }
}
if (-not $jobs) { Write-OK 'No BITS jobs found'; return }
foreach ($job in $jobs) {
$context = "$($job.DisplayName) $($job.JobState) $(($job.FileList | ForEach-Object { $_.RemoteName }) -join ' ')"
$suspicious, $reason = Test-IsSuspicious -CommandLine $context -Name $job.DisplayName
if ($suspicious -or $job.JobState -eq 'Suspended') {
$finalReason = if ($reason) { $reason } else { 'Suspended BITS job with suspicious context' }
Write-Finding -Category 'BITS Job' `
-Name $job.DisplayName `
-Detail "State: $($job.JobState) | ID: $($job.JobId)" `
-Reason $finalReason
$jobId = $job.JobId
Remove-PersistenceEntry -Label "BITS job $($job.JobId) cancelled" -RemoveBlock {
Get-BitsTransfer -JobId $jobId -ErrorAction Stop | Remove-BitsTransfer -ErrorAction Stop
}
} else {
Write-OK "BITS: $($job.DisplayName) [$($job.JobState)]"
}
}
}
# ==============================================================================
# MODULE 7 - Active Setup
# ==============================================================================
function Invoke-ScanActiveSetup {
Write-Banner "MODULE 7 - Active Setup"
$asPaths = @(
'HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Active Setup\Installed Components'
)
foreach ($asBase in $asPaths) {
if (-not (Test-Path $asBase)) { continue }
Get-ChildItem -Path $asBase | ForEach-Object {
$stubPath = (Get-ItemProperty -Path $_.PSPath -Name 'StubPath' -ErrorAction SilentlyContinue).StubPath
if ($stubPath) {
$suspicious, $reason = Test-IsSuspicious -CommandLine $stubPath -Name $_.PSChildName
if ($suspicious) {
Write-Finding -Category 'Active Setup' `
-Name $_.PSChildName `
-Detail "StubPath: $stubPath" `
-Reason $reason
$keyPath = $_.PSPath
Remove-PersistenceEntry -Label "Active Setup key: $($_.PSChildName)" -RemoveBlock {
Remove-Item -Path $keyPath -Recurse -Force -ErrorAction Stop
}
}
}
}
}
Write-OK 'Active Setup scan complete'
}
# ==============================================================================
# MODULE 8 - Disk Dropper Hunt
# ==============================================================================
function Invoke-ScanDropperScripts {
Write-Banner "MODULE 8 - Disk Dropper Script Hunt"
$huntPaths = @(
$env:TEMP, $env:TMP, "$env:APPDATA", "$env:LOCALAPPDATA\Temp",
"$env:LOCALAPPDATA\Microsoft", "$env:ProgramData", "$env:ProgramData\Microsoft",
'C:\Users\Public', 'C:\Users\Public\Documents', 'C:\Windows\Temp',
"$env:USERPROFILE\Downloads", "$env:USERPROFILE\Desktop"
) | Sort-Object -Unique
$scriptExtensions = @('*.ps1','*.vbs','*.bat','*.cmd','*.js','*.wsf','*.hta','*.py')
$found = 0
foreach ($huntDir in $huntPaths) {
if (-not (Test-Path $huntDir)) { continue }
foreach ($pattern in $scriptExtensions) {
$candidates = Get-ChildItem -Path $huntDir -Filter $pattern -Force -ErrorAction SilentlyContinue
foreach ($file in $candidates) {
if (Test-FileIsDropper -FilePath $file.FullName) {
$found++
Write-Finding -Category 'Dropper Script (disk)' `
-Name $file.Name `
-Detail "Path: $($file.FullName)" `
-Reason 'File content references payload IOC keyword'
$filePath = $file.FullName
Remove-PersistenceEntry -Label "Dropper deleted: $filePath" -RemoveBlock {
Remove-Item -Path $filePath -Force -ErrorAction Stop
}
}
}
}
}
if ($found -eq 0) { Write-OK 'No dropper scripts found in monitored directories' }
}
# ==============================================================================
# MODULE 9 - Kill Suspicious PowerShell Processes
# ==============================================================================
function Invoke-KillSuspiciousPowerShell {
Write-Banner "MODULE 9 - Kill Suspicious PowerShell Processes"
$killed = 0
$psProcs = Get-Process -Name "powershell","pwsh" -ErrorAction SilentlyContinue
foreach ($proc in $psProcs) {
try {
$wmi = Get-CimInstance Win32_Process -Filter "ProcessId=$($proc.Id)" -EA Stop
$cmd = $wmi.CommandLine
if ($cmd -match "pwned|Pwn3d|Set-Content.*pwned|Start-Sleep.*Set-Content" -or
$cmd -match "-Win Hidden.*Set-Content" -or
$cmd -match "pw.*ned\.txt") {
Write-Finding -Category 'Suspicious Process' `
-Name "PID $($proc.Id)" `
-Detail "Command: $($cmd.Substring(0,[Math]::Min(200,$cmd.Length)))" `
-Reason "Process attempting to create pwned.txt or contains payload keyword"
Remove-PersistenceEntry -Label "Kill PowerShell PID $($proc.Id)" -RemoveBlock {
Stop-Process -Id $proc.Id -Force -ErrorAction Stop
}
$killed++
}
} catch {}
}
if ($killed -eq 0) { Write-OK "No suspicious PowerShell processes found" }
}
# ==============================================================================
# MODULE 10 - Payload File Removal
# ==============================================================================
function Invoke-RemovePayload {
Write-Banner "MODULE 10 - Payload File Removal"
if (Test-Path $Config.PwnedFile) {
$content = Get-Content $Config.PwnedFile -Raw -ErrorAction SilentlyContinue
Write-Finding -Category 'Payload File' `
-Name $Config.PwnedFile `
-Detail "Content: $($content -replace "`n"," ")" `
-Reason 'Payload file exists - attacker persistence already fired'
$pFile = $Config.PwnedFile
Remove-PersistenceEntry -Label "Payload deleted: $Config.PwnedFile" -RemoveBlock {
Remove-Item -Path $pFile -Force -ErrorAction Stop
}
} else {
Write-OK "Payload file not present: $Config.PwnedFile"
}
Get-ChildItem -Path 'C:\Users\Public' -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match 'pwned|Pwn3d' -or (Test-FileIsDropper -FilePath $_.FullName) } |
ForEach-Object {
Write-Finding -Category 'Payload Artifact' `
-Name $_.Name `
-Detail $_.FullName `
-Reason 'File name or content matches payload IOC'
$iPath = $_.FullName
Remove-PersistenceEntry -Label "Artifact removed: $iPath" -RemoveBlock {
Remove-Item -Path $iPath -Force -ErrorAction Stop
}
}
}
# ==============================================================================
# MODULE 11 - GUID Pattern Folder Scanner
# ==============================================================================
function Invoke-ScanGuidFolders {
Write-Banner "MODULE 11 - GUID-Pattern Folder Scanner"
$guidPattern = '^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$'
$guidRoots = @($env:TEMP, $env:LOCALAPPDATA, "C:\Windows\Temp", "C:\Users\Public")
$found = 0
foreach ($root in $guidRoots) {
if (-not (Test-Path $root)) { continue }
Get-ChildItem -Path $root -Directory -Force -EA SilentlyContinue |
Where-Object { $_.Name -match $guidPattern } |
ForEach-Object {
$folderPath = $_.FullName
$ps1Files = Get-ChildItem $folderPath -Filter '*.ps1' -Force -Recurse -EA SilentlyContinue
$hasBase64 = $false
foreach ($f in $ps1Files) {
$raw = Get-Content $f.FullName -Raw -EA SilentlyContinue
if ($raw -match '[A-Za-z0-9+/]{100,}={0,2}') { $hasBase64 = $true }
}
$isKnownBad = ($_.Name -eq $Config.GuidFolderName)
if ($isKnownBad -or $hasBase64 -or ($ps1Files.Count -gt 0)) {
$found++
Write-Finding -Category 'GUID Folder' `
-Name $_.Name `
-Detail "Path: $folderPath | PS1: $($ps1Files.Count) | Base64: $hasBase64" `
-Reason "GUID-pattern folder with suspicious content"
Remove-PersistenceEntry -Label "GUID folder: $folderPath" -RemoveBlock {
Get-ChildItem $folderPath -Force -Recurse -EA SilentlyContinue |
ForEach-Object { try { $_.Attributes = 'Normal' } catch {} }
Remove-Item $folderPath -Recurse -Force -ErrorAction Stop
}
}
}
}
if ($found -eq 0) { Write-OK "No suspicious GUID-pattern folders found" }
}
# ==============================================================================
# MODULE 12 - Base64 Encoded PS1 Detector
# ==============================================================================
function Invoke-ScanBase64Encoded {
Write-Banner "MODULE 12 - Base64 Encoded PowerShell Detector"
$scanRoots = @($env:TEMP, $env:APPDATA, $env:LOCALAPPDATA, "C:\Users\Public", "C:\Windows\Temp", "C:\ProgramData")
$found = 0
foreach ($root in $scanRoots) {
if (-not (Test-Path $root)) { continue }
Get-ChildItem $root -Filter '*.ps1' -Recurse -Force -EA SilentlyContinue |
ForEach-Object {
try {
$raw = Get-Content $_.FullName -Raw -Encoding UTF8 -EA Stop
if ($raw -match '[A-Za-z0-9+/]{100,}={0,2}') {
$found++
$decoded = Get-DecodedPayload -FilePath $_.FullName
$preview = if ($decoded) {
$decoded.Substring(0, [Math]::Min(100, $decoded.Length)) -replace "`r`n|`n"," | "
} else { "(decode failed)" }
Write-Finding -Category 'Base64 Encoded PS1' `
-Name $_.Name `
-Detail "Path: $($_.FullName) | Decoded preview: $preview" `
-Reason "Base64-encoded PowerShell script detected"
Remove-PersistenceEntry -Label "Encoded PS1: $($_.FullName)" -RemoveBlock {
$_.Attributes = 'Normal'
Remove-Item $_.FullName -Force -ErrorAction Stop
}
}
} catch {}
}
}
if ($found -eq 0) { Write-OK "No Base64-encoded PS1 files detected" }
}
# ==============================================================================
# TRAY ICON NOTIFICATION FUNCTION
# ==============================================================================
function Show-TrayNotification {
param([string]$Title, [string]$Message, [string]$Icon = "Info")
$wshell = New-Object -ComObject Wscript.Shell
$popup = $wshell.Popup($Message, 3, $Title, 64 + 4096)
}
function Start-TrayIcon {
param([string]$WatchdogScriptPath)
$trayScript = @"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
`$watchdogProcess = Start-Process -FilePath "powershell.exe" -ArgumentList "-ExecutionPolicy Bypass -File `"$WatchdogScriptPath`"" -WindowStyle Hidden -PassThru
`$notifyIcon = New-Object System.Windows.Forms.NotifyIcon
`$notifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
`$notifyIcon.Text = "BlueTeam Defender Watchdog`nActive and Monitoring"
`$notifyIcon.Visible = `$true
`$contextMenu = New-Object System.Windows.Forms.ContextMenuStrip
`$statusItem = New-Object System.Windows.Forms.ToolStripMenuItem
`$statusItem.Text = "Status: ACTIVE - Monitoring for persistence"
`$statusItem.Enabled = `$false
`$contextMenu.Items.Add(`$statusItem) | Out-Null
`$contextMenu.Items.Add("-") | Out-Null
`$showItem = New-Object System.Windows.Forms.ToolStripMenuItem
`$showItem.Text = "Show Watchdog Results"
`$showItem.Add_Click({
Start-Process "notepad.exe" "$($Config.WatchdogResultsPath)"
})
`$contextMenu.Items.Add(`$showItem) | Out-Null
`$stopItem = New-Object System.Windows.Forms.ToolStripMenuItem
`$stopItem.Text = "Stop Watchdog"