-
Notifications
You must be signed in to change notification settings - Fork 10
/
PowerHunt.psm1
2981 lines (2463 loc) · 130 KB
/
PowerHunt.psm1
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
# -------------------------------------------
# Function: Invoke-PowerHunt
# -------------------------------------------
# Version: 0.66
# Author: Scott Sutherland (@_nullbind), NetSPI 2022
function Invoke-PowerHunt
{
<#
.SYNOPSIS
This is a modular threat hunting framework designed to perform data collection via PowerShell remoting and offline analysis using easy to build modules.
.PARAMETER Username
Local or domain account to authenticate with.
.PARAMETER Password
Local or domain account password to authenticate with.
.PARAMETER Credential
Local or domain credential.
.PARAMETER DomainController
Domain controller to communicate with for computer discovery.
.PARAMETER Threads
Number of runspace threads to use during ping and port scanning.
.PARAMETER RunSpaceTimeOut
RunSpaceTimeOut.
.PARAMETER CollectOnly
Only run collection modules, no analysis modules.
.PARAMETER AnalyzeOnly
Only run analysis modules against offline data. Requires OfflinePath.
.PARAMETER OfflinePath
Collection scan directory. Can either be from full scan or CollectOnly scan.
.PARAMETER ComputerName
Target single system, Active Directory discovery is disabled when using this method.
.PARAMETER ComputerList
Target list of computers with this file path, Active Directory discovery is disabled when using this method.
.PARAMETER ShowSummary
Display a table containing a summary for each module.
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -DomainController 10.1.1.1
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -DomainController 10.1.1.1 -Credentials domain\user
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -DomainController 10.1.1.1 -Username domain\user -Password 'SecretPasswordHere!'
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -ComputerName Desktop123
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -ComputerList c:\temp\computers.txt
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -Threads 100 -CollectOnly
.EXAMPLE
PS C:\> Invoke-PowerHunt -OutputDirectory "c:\temp" -AnalyzeOnly -OfflinePath c:\temp\Hunt-032120222126
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,
HelpMessage = 'Domain user to authenticate with domain\user. For computer lookup.')]
[string]$Username,
[Parameter(Mandatory = $false,
HelpMessage = 'Domain password to authenticate with domain\user. For computer lookup.')]
[string]$Password,
[Parameter(Mandatory = $false,
HelpMessage = 'Credentials to use when connecting to a Domain Controller. For computer lookup.')]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
[Parameter(Mandatory = $false,
HelpMessage = 'Domain controller for Domain and Site that you want to query against. For computer lookup.')]
[string]$DomainController,
[Parameter(Mandatory = $false,
HelpMessage = 'Number of threads to process at once.')]
[int]$Threads = 100,
[Parameter(Mandatory = $true,
HelpMessage = 'Directory to output files to.')]
[string]$OutputDirectory,
[Parameter(Mandatory = $false,
HelpMessage = 'Runspace time out.')]
[int]$RunSpaceTimeOut = 15,
[Parameter(Mandatory = $false,
HelpMessage = 'Show runspace errors if they occur.')]
[switch] $ShowRunpaceError,
[Parameter(Mandatory = $false,
HelpMessage = 'Only run collection modules.')]
[switch] $CollectOnly,
[Parameter(Mandatory = $false,
HelpMessage = 'Only run analysis modules against offline data. Requires OfflinePath.')]
[switch] $AnalyzeOnly,
[Parameter(Mandatory = $false,
HelpMessage = 'Collection scan directory. Can either be from full scan or CollectOnly scan.')]
[string]$OfflinePath,
[Parameter(Mandatory = $false,
HelpMessage = 'Target a single computer. This will disable LDAP discovery.')]
[string]$ComputerName,
[Parameter(Mandatory = $false,
HelpMessage = 'Target a list of computers. This will disable LDAP discovery.')]
[string]$ComputerList,
[Parameter(Mandatory = $false,
HelpMessage = 'Display a table containing a summary for each module. ')]
[switch] $ShowSummary
)
Begin
{
# Create data table to store module summary data
$ModuleOutputSummary = New-Object System.Data.DataTable
$null = $ModuleOutputSummary.Columns.Add("ModuleType")
$null = $ModuleOutputSummary.Columns.Add("CollectModule")
$null = $ModuleOutputSummary.Columns.Add("CollectSource")
$null = $ModuleOutputSummary.Columns.Add("AnalyzeModule")
$null = $ModuleOutputSummary.Columns.Add("AnalyzeModuleDesc")
$null = $ModuleOutputSummary.Columns.Add("InstanceType")
$null = $ModuleOutputSummary.Columns.Add("InstanceCount")
$null = $ModuleOutputSummary.Columns.Add("ComputerCount") # Computers with 1 or more instances
# Set target mode
$TargetMode = "Active Directory Computers"
if($ComputerName){
$TargetMode = "Single Computer"
}
if($ComputerList){
$TargetMode = "Computer List"
}
# Set variables
$Time = Get-Date -UFormat "%m/%d/%Y %R"
$GlobalThreadCount = $Threads
$AuthMode = "Current User"
# Check for credential
if($Credential.UserName){
$AuthMode = "Credential"
}
# Check for username and password
if($Username -and $Password){
$secpass = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Username, $secpass)
$AuthMode = "Username and Password"
}
Write-Output " ==========================================="
Write-Output " PowerHunt"
Write-Output " ==========================================="
Write-Output " Author: Scott Sutherland (@_nullbind), NetSPI"
Write-Output " -------------------------------------------"
Write-Output " [*][$Time] Authentication Mode : $AuthMode"
Write-Output " [*][$Time] Computer Target Mode: $TargetMode"
# Check for CollectOnly mode
if($CollectOnly){
Write-Output " [*][$Time] COLLECT ONLY MODE"
}
# Check for AnalyzeOnly mode
if($AnalyzeOnly){
Write-Output " [*][$Time] ANALYZE ONLY MODE"
}
# Create output directory
if(Test-Path $OutputDirectory){
# Create sub directory for output
try{
if(-not $AnalyzeOnly){
# Verify output directory path
$FolderDateTime = Get-Date -Format "MMddyyyyHHmmss"
$OutputDirectory = "$OutputDirectory\Hunt-$FolderDateTime"
Write-Output " [*][$Time] Output Directory : $OutputDirectory"
# Create sub directories
mkdir $OutputDirectory | Out-Null
mkdir "$OutputDirectory\collection" | Out-Null
mkdir "$OutputDirectory\analysis" | Out-Null
mkdir "$OutputDirectory\analysis\suspiciousartifacts" | Out-Null
mkdir "$OutputDirectory\analysis\anomalies" | Out-Null
mkdir "$OutputDirectory\discovery" | Out-Null
}
}catch{
Write-Output " [x][$Time] The $OutputDirectory was not writable."
Write-Output " [!][$Time] Aborting operation."
break
}
}
# Run collection if analyze only not set
if(-not $AnalyzeOnly){
# Check for modules direcroty
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if(Test-Path .\windows\modules){
# Write-Output " [*][$Time] The windows\modules directory was found."
}else{
Write-Output " [x][$Time] The windows\modules directory was not found."
Write-Output " [!][$Time] Aborting operation."
break
}
# Get start time
$StartTime = Get-Date
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Start active testing"
$StopWatch = [system.diagnostics.stopwatch]::StartNew()
Write-Output " -------------------------------------------"
Write-Output " ENABLING POWERSHELL REMOTING"
Write-Output " -------------------------------------------"
# Check for local administrator privileges
if ((New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false){
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [x][$Time] This is not a privileged processed, aborting operation."
Write-Output " [!][$Time] Make sure to run this in a privileged process."
Write-Output " [*][$Time] Below are the command to configure PS Remoting:"
Write-Output " [*][$Time] Enable-PSRemoting force"
Write-Output " [*][$Time] Set-Service WinRM StartMode Automatic"
Write-Output " [*][$Time] Set-Item WSMan:localhost\client\trustedhosts -value *"
break
}else{
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Confirmed local administrative privileges."
Write-Output " [*][$Time] Checking if PS Remoting is enabled..."
# Check if ps remoting is enabled
try{
# Test connection
Test-WSMan -ComputerName $env:COMPUTERNAME | Out-Null
Write-Output " [*][$Time] PS Remoting appears to be enabled."
}catch{
# Enable ps remoting
Write-Output " [x][$Time] PSRemoting appears to be disabled."
Write-Output " [*][$Time] Enabling PSRemoting..."
#Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private -ErrorAction SilentlyContinue
Enable-PSRemoting -Force -SkipNetworkProfileCheck -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
# Set start mode to automatic
Set-Service WinRM -StartMode Automatic -ErrorAction SilentlyContinue | Out-Null
}
# Trust all hosts
$Time = Get-Date -UFormat "%m/%d/%Y %R"
# Write-Output " [*][$Time] Trust configuration check..."
try{
Set-Item WSMan:localhost\client\trustedhosts -value * -Force -ErrorAction SilentlyContinue | Out-Null
# Write-Output " [*][$Time] Trust configuration updated successfully."
}catch{
Write-Output " [x][$Time] Trust configuration update failed."
Write-Output " [!][$Time] Aborting operation."
break
}
# Get service status
$ServiceStatus = Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}
# Get trust status
$TrustStatus = Get-Item WSMan:\localhost\Client\TrustedHosts
# One last configuration check
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if($ServiceStatus.State -eq "Running" -and $TrustStatus.Value -eq '*'){
Write-Output " [*][$Time] Local PowerShell Remoting requirements met."
}else{
Write-Output " [x][$Time] Enabling PowerShell Remoting failed."
Write-Output " [!][$Time] Aborting operation."
break
}
}
# ----------------------------------------------------------------------
# Target: Single Computer
# ----------------------------------------------------------------------
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if($ComputerName){
# Set target to single computer
Write-Output " -------------------------------------------"
Write-Output " TARGET: Single Computer"
Write-Output " -------------------------------------------"
Write-Output " [*][$Time] - $ComputerName"
$DomainComputers = $ComputerName | foreach{$object=new-object psobject;$object|add-member ComputerName $_;$object}
$ComputerCount = 1
$DomainComputers | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Single-Computer.csv"
}
# ----------------------------------------------------------------------
# Target: List of Computers
# ----------------------------------------------------------------------
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if($ComputerList){
# Set target to single computer
Write-Output " -------------------------------------------"
Write-Output " TARGET: Computer List"
Write-Output " -------------------------------------------"
Write-Output " [*][$Time] - $ComputerList"
# Test computer list path
if(Test-Path $ComputerList){
# Get computer list
$DomainComputers = gc $ComputerList | foreach{$object=new-object psobject;$object|add-member ComputerName $_;$object}
$ComputerCount = $DomainComputers | measure | select count -ExpandProperty count
$DomainComputers | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computer-list.csv"
}else{
Write-Output " [!][$Time] - Invalid path."
Write-Output " [x][$Time] - Aborting operation."
break
}
}
# ----------------------------------------------------------------------
# Target: Domain Computers
# ----------------------------------------------------------------------
# Only perform discovery if hosts are not provided
if(-not $ComputerList -and -not $ComputerName){
# Set target domain
Write-Output " -------------------------------------------"
Write-Output " DISCOVERY: DOMAIN COMPUTERS - LDAP QUERY"
Write-Output " -------------------------------------------"
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Attempting to access domain controller..."
$DCRecord = Get-LdapQuery -LdapFilter "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))" -DomainController $DomainController -Credential $Credential | select -first 1 | select properties -expand properties -ErrorAction SilentlyContinue
[string]$DCHostname = $DCRecord.dnshostname
[string]$DCCn = $DCRecord.cn
[string]$TargetDomain = $DCHostname -replace ("$DCCn\.","")
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if($DCHostname)
{
Write-Output " [*][$Time] Successful connection to domain controller: $DCHostname"
}else{
Write-Output " [x][$Time] There appears to have been an error connecting to the domain controller."
Write-Output " [!][$Time] Aborting."
break
}
# Status user
Write-Output " [*][$Time] Performing LDAP query for computers associated with the $TargetDomain domain"
# Get domain computers
$DomainComputersRecord = Get-LdapQuery -LdapFilter "(objectCategory=Computer)" -DomainController $DomainController -Credential $Credential
$DomainComputers = $DomainComputersRecord |
foreach{
$DnsHostName = [string]$_.Properties['dnshostname']
if($DnsHostName -notlike ""){
$object = New-Object psobject
$Object | Add-Member Noteproperty ComputerName $DnsHostName
$Object
}
}
# Status user
$ComputerCount = $DomainComputers.count
Write-Output " [*][$Time] - $ComputerCount computers found"
# Save results
# Write-Output " [*][$Time] - Saving to $OutputDirectory\Hunt-Target-Domain-Computers.csv"
$DomainComputers | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Domain-Computers.csv"
# $null = Convert-DataTableToHtmlTable -DataTable $DomainComputers -Outfile "$OutputDirectory\discovery\Hunt-Target-Domain-Computers.html" -Title "Domain Computers" -Description "This page shows the domain computers discovered for the $TargetDomain Active Directory domain."
$DomainComputersFile = "Hunt-Target-Domain-Computers.csv"
#$DomainComputersFileH = "Hunt-Target-Domain-Computers.html"
#Write-Output " [*][$Time] Output directory: $OutputDirectory"
}
# ----------------------------------------------------------------------
# Identify computers that respond to ping reqeusts
# ----------------------------------------------------------------------
Write-Output " -------------------------------------------"
Write-Output " DISCOVERY: PING SCANNING"
Write-Output " -------------------------------------------"
# Status user
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Pinging $ComputerCount computers"
# Ping computerss
$PingResults = $DomainComputers | Invoke-Ping -Throttle $GlobalThreadCount
# select computers that respond
$ComputersPingable = $PingResults |
foreach {
$PingComputerName = $_.address
$status = $_.status
if($status -like "Responding"){
$object = new-object psobject
$Object | add-member Noteproperty ComputerName $PingComputerName
$Object | add-member Noteproperty status $status
$Object
}
}
# Status user
$Time = Get-Date -UFormat "%m/%d/%Y %R"
$ComputerPingableCount = $ComputersPingable | measure | select count -expandproperty count
Write-Output " [*][$Time] - $ComputerPingableCount computers responded to ping requests."
# Stop if no hosts are accessible
If ($ComputerPingableCount -eq 0)
{
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [x][$Time] - Aborting."
break
}
# Save results
$Time = Get-Date -UFormat "%m/%d/%Y %R"
# Write-Output " [*][$Time] - Saving to $OutputDirectory\Hunt-Target-Computers-Pingable.csv"
$ComputersPingable | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computers-Pingable.csv"
#$null = Convert-DataTableToHtmlTable -DataTable $ComputersPingable -Outfile "$OutputDirectory\discovery\Hunt-Domain-Computers-Pingable.html" -Title "Domain Computers: Ping Response" -Description "This page shows the domain computers for the $TargetDomain Active Directory domain that responded to ping requests."
$ComputersPingableFile = "Hunt-Target-Computers-Pingable.csv"
#$ComputersPingableFileH = "Hunt-Target-Computers-Pingable.html"
Write-Output " -------------------------------------------"
Write-Output " DISCOVERY: PORT SCANNING `(5985/5986`)"
Write-Output " -------------------------------------------"
# ----------------------------------------------------------------------
# Identify computers that have TCP 5985 open and accessible
# ----------------------------------------------------------------------
# Status user
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Checking if TCP Port 5985 (NonSSL) is open on $ComputerPingableCount computers"
# Get clean list of pingable computers
$ComputersPingableClean = $ComputersPingable | Select-Object ComputerName
# Create script block to port scan tcp 5985
$MyScriptBlock = {
$ComputerName = $_.ComputerName
try{
$Socket = New-Object System.Net.Sockets.TcpClient($ComputerName,"5985")
if($Socket.Connected)
{
$Status = "Open"
$Socket.Close()
}
else
{
$Status = "Closed"
}
}
catch{
$Status = "Closed"
}
if($Status -eq "Open")
{
$object = new-object psobject
$Object | add-member Noteproperty ComputerName $computername
$Object | add-member Noteproperty 5985status $status
$Object
}
}
# Perform port scan of tcp 5985 threaded
$Computers5985Open = $ComputersPingableClean | Invoke-Parallel -ScriptBlock $MyScriptBlock -ImportSessionFunctions -ImportVariables -Throttle $GlobalThreadCount -RunspaceTimeout $RunSpaceTimeOut -ErrorAction SilentlyContinue
# Status user
$Time = Get-Date -UFormat "%m/%d/%Y %R"
$Computers5985OpenCount = $Computers5985Open | measure | select count -ExpandProperty count
Write-Output " [*][$Time] - $Computers5985OpenCount computers have TCP port 5985 open."
# Save results
# Write-Output " [*][$Time] - Saving to $OutputDirectory\Hunt-Target-Computers-Open5985.csv"
$Computers5985Open | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computers-Open5985.csv"
#$null = Convert-DataTableToHtmlTable -DataTable $Computers5985Open -Outfile "$OutputDirectory\discovery\Hunt-Target-Computers-Open5985.html" -Title "Domain Computers: Port 5985 Open" -Description "This page shows the domain computers for the $TargetDomain Active Directory domain with port 5985 open."
$Computers5985OpenFile = "Hunt-Target-Computers-Open5985.csv"
#$Computers5985OpenFileH ="Hunt-Target-Computers-Open5985.html"
# ----------------------------------------------------------------------
# Identify computers that have TCP 5986 open and accessible
# ----------------------------------------------------------------------
# Status user
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Checking if TCP Port 5986 (SSL) is open on $ComputerPingableCount computers"
# Get clean list of pingable computers
$ComputersPingableClean = $ComputersPingable | Select-Object ComputerName
# Create script block to port scan tcp 5986
$MyScriptBlock = {
$ComputerName = $_.ComputerName
try{
$Socket = New-Object System.Net.Sockets.TcpClient($ComputerName,"5986")
if($Socket.Connected)
{
$Status = "Open"
$Socket.Close()
}
else
{
$Status = "Closed"
}
}
catch{
$Status = "Closed"
}
if($Status -eq "Open")
{
$object = new-object psobject
$Object | add-member Noteproperty ComputerName $computername
$Object | add-member Noteproperty 5986status $status
$Object
}
}
# Perform port scan of tcp 5986 threaded
$Computers5986Open = $ComputersPingableClean | Invoke-Parallel -ScriptBlock $MyScriptBlock -ImportSessionFunctions -ImportVariables -Throttle $GlobalThreadCount -RunspaceTimeout $RunSpaceTimeOut -ErrorAction SilentlyContinue
# Status user
$Computers5986OpenCount = $Computers5986Open | measure | select count -ExpandProperty count
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - $Computers5986OpenCount computers have TCP port 5986 open."
# Save results
# Write-Output " [*][$Time] - Saving to $OutputDirectory\Hunt-Target-Computers-Open5986.csv"
$Computers5986Open | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computers-Open5986.csv"
#$null = Convert-DataTableToHtmlTable -DataTable $Computers5986Open -Outfile "$OutputDirectory\discovery\Hunt-Target-Computers-Open5986.html" -Title "Domain Computers: Port 5986 Open" -Description "This page shows the domain computers for the $TargetDomain Active Directory domain with port 5986 open."
$Computers5986OpenFile = "Hunt-Target-Computers-Open5986.csv"
#$Computers5986OpenFileH ="Hunt-Target-Computers-Open5986.html"
# ----------------------------------------------------------------------
# Identify PS Remoting Targets
# ----------------------------------------------------------------------
# Add percentage that likley support ps remoting
if($Computers5986OpenCount -eq 0 -and $Computers5985OpenCount -eq 0){
Write-Output " [x][$Time] - PS Remoting does not appear to be available."
Write-Output " [!][$Time] - Aborting operation."
break
}else{
# Combine host lists
Write-Output " [*][$Time] Creating PS Remoting Target List."
$PsRemotingTargetsAll = $Computers5986Open + $Computers5985Open
$PsRemotingTargetsAll = $PsRemotingTargetsAll | select computername -Unique
$PsRemotingTargetsAllCount = $PsRemotingTargetsAll | measure | select count -ExpandProperty count
# Save results
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - $PsRemotingTargetsAllCount computers will be targeted."
# Write-Output " [*][$Time] - Saving to $OutputDirectory\discovery\Hunt-Target-Computers-PsRemoting.csv"
$PsRemotingTargetsAll | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computers-PsRemoting-Targets.csv"
}
Write-Output " -------------------------------------------"
Write-Output " COLLECTION: ESTABLISH PS REMOTING SESSIONS"
Write-Output " -------------------------------------------"
Write-Output " [*][$Time] - Attempting to establish PS Remoting sessions with $PsRemotingTargetsAllCount computers."
$PsRemotingTargetsAll | select ComputerName |
Foreach{
try{
# Try without ssl
New-PSSession -ErrorAction SilentlyContinue -ComputerName $_.ComputerName -Credential $Credential | Out-Null
}catch{
# Try with ssl if not access denied
if ($Error[0] -notlike "*Access is denied.*"){
New-PSSession -UseSSL -ErrorAction SilentlyContinue -ComputerName $_.ComputerName -Credential $Credential | Out-Null
}
}
}
$SessionCount = (Get-PSSession | where State -like "*Opened*").count
Get-PSSession | where State -like "*Opened*" | Export-Csv -NoTypeInformation "$OutputDirectory\discovery\Hunt-Target-Computers-PsRemoting-Sessions.csv"
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - $SessionCount PS Remoting sessions were established."
if($SessionCount -eq 0){
Write-Output " [!][$Time] - Aborting operation."
break
}
Write-Output " -------------------------------------------"
Write-Output " COLLECTION: RUN ALL MODULES"
Write-Output " -------------------------------------------"
# Get list of collection modules
$CollectionModules = Get-ChildItem .\windows\modules\collection
$CollectionModulesCount = $CollectionModules | measure | select count -ExpandProperty count
Write-Output " [*][$Time] $CollectionModulesCount collection modules will be run against $SessionCount sessions."
# Load and run each module
$CurrentModulesCount = 0
$CollectionModules |
foreach{
# Counter
$CurrentModulesCount = $CurrentModulesCount + 1
# Get time
$Time = Get-Date -UFormat "%m/%d/%Y %R"
# Get file path
$ModuleFilePath = $_.fullname
# Parse module name from file
$ModuleName= $_.name -replace(".ps1","")
$CollectionDataSource = $_.name -replace(".ps1","") -replace("collect-","")
$ModuleStartTime = Get-Date
# Run module
Write-Output " [*][$Time] - `($CurrentModulesCount of $CollectionModulesCount`) $ModuleName"
$MyCommand = Get-Content $_.fullname -Raw
$Results = Invoke-Command -Session (Get-PSSession | where state -like "Opened") -ScriptBlock {Invoke-Expression -Command "$args"} -ArgumentList $MyCommand -ErrorAction SilentlyContinue
$ModuleStopTime = Get-Date
$ModuleDuration = $ModuleStopTime - $ModuleStartTime
$Time = Get-Date -UFormat "%m/%d/%Y %R"
# Save output
$FileName = $_.name -replace(".ps1",".csv")
$Time = Get-Date -UFormat "%m/%d/%Y %R"
$Results | Export-Csv -NoTypeInformation "$OutputDirectory\collection\Hunt-$FileName"
# Get instance count
$ResultsCount = $Results | measure |select count -ExpandProperty count
# Computer count
if($ResultsCount -eq 0){
$CollectModuleAffectedComputerCount = 0
}else{
$CollectModuleAffectedComputerCount = $Results | select PSComputerName -Unique | measure | select count -ExpandProperty count
}
# Save summary metrics
$null = $ModuleOutputSummary.Rows.Add("Collection","$ModuleName","$CollectionDataSource","NA","NA","NA","$ResultsCount","$CollectModuleAffectedComputerCount")
}
}
# Run analysis modules if collectonly not set
if( -not $CollectOnly){
Write-Output " -------------------------------------------"
Write-Output " ANALYSIS: RUN ALL MODULES"
Write-Output " -------------------------------------------"
# Check offline path if analysis model
$Time = Get-Date -UFormat "%m/%d/%Y %R"
if($AnalyzeOnly){
if(-not $OfflinePath){
Write-Output " [!][$Time] Analysis only mode failed. Missing OfflinePath."
Write-Output " [x][$Time] Aborting operation."
break
}else{
if(Test-Path "$OfflinePath"){
# Override outputdirectory if analysisonly mode
$OutputDirectory = $OfflinePath
}else{
Write-Output " [!][$Time] Analysis only mode failed. Bad OfflinePath."
Write-Output " [x][$Time] Aborting operation."
break
}
}
}
# Get list of collection modules
$CollectionModules = Get-ChildItem .\windows\modules\collection
$CollectionModulesCount = $CollectionModules | measure | select count -ExpandProperty count
# Get analysis module count
$AnalysisModules = Get-ChildItem -Recurse .\windows\modules\analysis
$AnalysisModulesCount = $AnalysisModules | measure | select count -ExpandProperty count
Write-Output " [*][$Time] $AnalysisModulesCount analysis modules will be run against $CollectionModulesCount data sources."
# Review each collection module data source
$CollectionModulesCountP = 0
$CollectionModules |
foreach{
# Data Source Counter
$CollectionModulesCountP = $CollectionModulesCountP + 1
# Parse module name from file
$CollectionDataSource = $_.name -replace(".ps1","") -replace("collect-","")
$CollectionModuleName = $_.name -replace(".ps1","")
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] Data Source `($CollectionModulesCountP of $CollectionModulesCount`): $CollectionDataSource"
# Generate data source file path
$CollectionModuleFile = $_.name -replace(".ps1",".csv")
if($OfflinePath){ $TargetDomain = '*' }
$CollectionDataSourcePath = "$OutputDirectory\collection\Hunt-$CollectionModuleFile"
if($OfflinePath){ $TargetDomain = "OfflineAnalysis" }
# ////////
# Analysis Module: Searching Techniques
# ////////
# Select analysis modules that match the current data source name
# This is based on the collection file name
$AnalysisModulesT = Get-ChildItem .\windows\modules\analysis\search | where fullname -like "*$CollectionDataSource*"
$AnalysisModulesCountT = $AnalysisModulesT | measure | select count -ExpandProperty count
if($AnalysisModulesCountT -eq 0){
Write-Output " [*][$Time] 0 search analysis modules exist for this data source."
}else{
Write-Output " [*][$Time] $AnalysisModulesCountT search analysis modules found, loading data source."
# load the data source data here
$CollectedData = Import-Csv $CollectionDataSourcePath
}
# Data Source Counter
$AnalysisModulesCountP = 0
# Process each analysis module
$AnalysisModulesT |
Foreach {
# Set analysis counter
$AnalysisModulesCountP = $AnalysisModulesCountP + 1
# Parse analysis file path
$AnalysisModuleFilePath = $_.fullname
# Parse analysis module name
$AnalysisModuleName = $_.name -replace(".ps1","")
# Analysis subdirectory
$AnalysisSubDir = 'suspiciousartifacts\'
# Set module fields
$ModuleType = "Analysis"
$AnalysisType = "Suspicious Artifact"
# Load and run analysis module
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - `($AnalysisModulesCountP of $AnalysisModulesCountT`) $AnalysisModuleName"
# Get module code
$AnalysisCommand = Get-Content $AnalysisModuleFilePath -Raw
# Run module code
Invoke-Expression $AnalysisCommand
}
# ////////
# Analysis Module: Stacking / Frequency Analysis Techniques
# ////////
# Select analysis modules that match the current data source name
# This is based on the collection file name
$AnalysisModulesT = Get-ChildItem .\windows\modules\analysis\stack | where fullname -like "*$CollectionDataSource*"
$AnalysisModulesCountT = $AnalysisModulesT | measure | select count -ExpandProperty count
if($AnalysisModulesCountT -eq 0){
Write-Output " [*][$Time] 0 stack analysis modules exist for this data source."
}else{
Write-Output " [*][$Time] $AnalysisModulesCountT stack analysis modules found, loading data source."
# load the data source data here
$CollectedData = Import-Csv $CollectionDataSourcePath
}
# Data Source Counter
$AnalysisModulesCountP = 0
# Process each analysis module
$AnalysisModulesT |
Foreach {
# Set analysis counter
$AnalysisModulesCountP = $AnalysisModulesCountP + 1
# Parse analysis file path
$AnalysisModuleFilePath = $_.fullname
# Parse analysis module name
$AnalysisModuleName = $_.name -replace(".ps1","")
# Analysis subdirectory
$AnalysisSubDir = 'anomalies\'
# Set module fields
$ModuleType = "Analysis"
$AnalysisType = "Anomaly"
# Load and run analysis module
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - `($AnalysisModulesCountP of $AnalysisModulesCountT`) $AnalysisModuleName"
# Get module code
$AnalysisCommand = Get-Content $AnalysisModuleFilePath -Raw
# Run module code
Invoke-Expression $AnalysisCommand
}
}
Write-Output " -------------------------------------------"
Write-Output " REPORTING: RUN ALL MODULES"
Write-Output " -------------------------------------------"
Write-Output " - HTML `(pending`)"
<#
# Calculate Summary: Computers
$ComputerCount
$ComputerPingableCount
$Computers5986OpenCount
$Computers5985OpenCount
$SessionCount
# Total computers with one or more anomalies + %
# Total computers with one or more suspicious artifacts + %
# Calculate Summary: Collection Modules
# Total number of modules
$CollectionModulesCount
# Total number of modules with one or more suspicious artifacts or anomalies + % of provided
$CollectModuleWithFindingsAll = $ModuleOutputSummary | where ModuleType -eq "Collection"
$CollectModuleWithFindings = $ModuleOutputSummary | where ModuleType -eq "Collection" | Where InstanceCount -GT 0
$CollectModuleWithFindingsCount = $CollectModuleWithFindings | measure | select count -ExpandProperty count
# Calculate Summary: Analysis Modules
# Total number of modules
$AnalysisModulesCount
# Total number of modules with one or more suspicious artifacts or anomalies + % of provided
$AnalysisModuleWithFindingsAll = $ModuleOutputSummary | where ModuleType -eq "Analysis"
$AnalysisModuleWithFindings = $ModuleOutputSummary | where ModuleType -eq "Analysis" | Where InstanceCount -GT 0
$AnalysisModuleWithFindingsCount = $AnalysisModuleWithFindings | measure | select count -ExpandProperty count
# Calculate Summary: Suspicous Artifacts
# Get affected
$SusArtModuleWithFindingsAll = $ModuleOutputSummary | where FindingType -eq "Suspicious Artifact"
$SusArtModuleWithFindings = $SusArtModuleWithFindingsAll | Where InstanceCount -GT 0
$SusArtAffectedCollectModules = $SusArtModuleWithFindings | select CollectModule -Unique
$SusArtAffectedCollectModulesCount = $SusArtAffectedCollectModules | measure | select count -ExpandProperty count
$SusArtAffectedAnalyzeModules = $SusArtModuleWithFindings | select AnalyzeModule -Unique
$SusArtAffectedAnalyzeModulesCount = $SusArtAffectedAnalyzeModules | measure | select count -ExpandProperty count
# Calculate Summary: Anomalies
# Get affected
$AnomalyModuleWithFindingsAll = $ModuleOutputSummary | where FindingType -eq "Anomaly"
$AnomalyModuleWithFindings = $AnomalyModuleWithFindingsAll | Where InstanceCount -GT 0
$SusArtAffectedCollectModules = $AnomalyModuleWithFindings | select CollectModule -Unique
$SusArtAffectedCollectModulesCount = $SusArtAffectedCollectModules | measure | select count -ExpandProperty count
$SusArtAffectedAnalyzeModules = $AnomalyModuleWithFindings | select AnalyzeModule -Unique
$SusArtAffectedAnalyzeModulesCount = $SusArtAffectedAnalyzeModules | measure | select count -ExpandProperty count
#>
# Generate HTML summary report
}
# Shutdown active sessions if not offline mode / analysis only
if(-not $OfflinePath){
Write-Output " -------------------------------------------"
Write-Output " SHUTDOWN"
Write-Output " -------------------------------------------"
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - Stopping active testing"
Write-Output " [*][$Time] - Terminating $SessionCount PowerShell Remoting sessions."
Get-PSSession | Disconnect-PSSession -ErrorAction SilentlyContinue | Out-Null
Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue | Out-Null
$Time = Get-Date -UFormat "%m/%d/%Y %R"
Write-Output " [*][$Time] - All sessions terminated."
# Final user status
$StopTime = Get-Date
$ScanDuration = $StopTime - $StartTime
Write-Output " [*][$Time] - Test duration: $ScanDuration"
}
# Clean data source
$ModuleOutputSummaryClean = $ModuleOutputSummary |
foreach{
# Get variables
$ModuleType = $_.ModuleType
$CollectModule = $_.CollectModule
$CollectSource = $_.CollectSource
$AnalyzeModule = $_.AnalyzeModule
$AnalyzeModuleDesc = $_.AnalyzeModuleDesc
$InstanceType = $_.InstanceType
$InstanceCount = $_.InstanceCount
$ComputerCount = $_.ComputerCount
# Get length for $CollectSource - apparently not needed for powershell substrings
$CollectSourceLen = $CollectSource.Length
# Get offset of second -; 017-04-wmi-providers
$CollectSourceOffSet = 1 + (($CollectSource | select-string "-" -AllMatches).Matches | select index -first 2 -ExpandProperty index | select -last 1)
# Select Clean name
$CollectSourceNew = $CollectSource.Substring($CollectSourceOffSet).Replace("-"," ").ToUpper()
# Build object
$object = New-Object PSObject
$object | add-member ModuleType $ModuleType
$object | add-member CollectModule $CollectModule
$object | add-member CollectSource $CollectSourceNew
$object | add-member AnalyzeModule $AnalyzeModule
$object | add-member AnalyzeModuleDesc $AnalyzeModuleDesc
$object | add-member InstanceType $InstanceType
$object | add-member InstanceCount $InstanceCount
$object | add-member ComputerCount $ComputerCount
# Return object
$object
}
# Save summary data to file
$ModuleOutputSummaryClean | Export-Csv -NoTypeInformation "$OutputDirectory\Hunt-Module-Summary-Table.csv"
# Show $ModuleOutputSummary
if($ShowSummary -and $ModuleOutputSummary){
$ModuleOutputSummaryClean
}
}
}
# -------------------------------------------
# Function: Get-LdapQuery
# -------------------------------------------
# Author: Will Schroeder
# Modifications: Scott Sutherland
function Get-LdapQuery
{
<#
.SYNOPSIS
Used to query domain controllers via LDAP. Supports alternative credentials from non-domain system
Note: This will use the default logon server by default.
.PARAMETER Username
Domain account to authenticate to Active Directory.
.PARAMETER Password
Domain password to authenticate to Active Directory.
.PARAMETER Credential
Domain credential to authenticate to Active Directory.
.PARAMETER DomainController
Domain controller to authenticated to. Requires username/password or credential.
.PARAMETER LdapFilter
LDAP filter.
.PARAMETER LdapPath
Ldap path.
.PARAMETER $Limit
Maximum number of Objects to pull from AD, limit is 1,000.".
.PARAMETER SearchScope
Scope of a search as either a base, one-level, or subtree search, default is subtree..
.EXAMPLE
PS C:\temp> Get-DomainObject -LdapFilter "(&(servicePrincipalName=*))"
.EXAMPLE
PS C:\temp> Get-DomainObject -LdapFilter "(&(servicePrincipalName=*))" -DomainController 10.0.0.1:389
It will use the security context of the current process to authenticate to the domain controller.
IP:Port can be specified to reach a pivot machine.
.EXAMPLE
PS C:\temp> Get-DomainObject -LdapFilter "(&(servicePrincipalName=*))" -DomainController 10.0.0.1 -Username Domain\User -Password Password123!
.Notes
This was based on Will Schroeder's Get-ADObject function from https://github.com/PowerShellEmpire/PowerTools/blob/master/PowerView/powerview.ps1
#>