forked from SpecterOps/MSSQLHound
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMSSQLHound.ps1
More file actions
9458 lines (8244 loc) · 499 KB
/
MSSQLHound.ps1
File metadata and controls
9458 lines (8244 loc) · 499 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
<#
.SYNOPSIS
MSSQLHound: PowerShell collector for adding MSSQL attack paths to BloodHound with OpenGraph
.DESCRIPTION
Author: Chris Thompson (@_Mayyhem) at SpecterOps
Purpose:
Collects BloodHound OpenGraph compatible data from one or more MSSQL servers into individual files, then zips them
- Example: mssql-bloodhound-20250724-115610.zip
System Requirements:
- PowerShell 4.0 or higher
- Target is running SQL Server 2005 or higher
Minimum Permissions:
Windows Level:
- Active Directory domain context with line of sight to a domain controller
MSSQL Server Level:
- **CONNECT SQL** (default for new logins)
- **VIEW ANY DATABASE** (default for new logins)
Recommended Permissions:
MSSQL Server Level:
- **VIEW ANY DEFINITION** permission or ##MS_DefinitionReader## role membership (available in versions 2022+)
- Needed to read server principals and their permissions
- Without one of these permissions, there will be false negatives (invisible server principals)
- **VIEW SERVER PERFORMANCE STATE** permission or ##MSS_ServerPerformanceStateReader## role membership (available in versions 2022+) or local Administrators group privileges on the target (fallback for WMI collection)
- Only used for service account collection
MSSQL Database Level:
- **CONNECT ANY DATABASE** server permission (available in versions 2014+) or ##MS_DatabaseConnector## role membership (available in versions 2022+) or login maps to a database user with CONNECT on individual databases
- Needed to read database principals and their permissions
- Login maps to **msdb database user with db_datareader** role or with SELECT permission on:
- msdb.dbo.sysproxies
- msdb.dbo.sysproxylogin
- msdb.dbo.sysproxysubsystem
- msdb.dbo.syssubsystems
- Only used for proxy account collection
.PARAMETER Help
Display usage information
.PARAMETER OutputFormat
Supported values:
- BloodHound (default): OpenGraph implementation, outputs .zip containing .json files per server
- BHGeneric: (work in progress) OpenGraph implementation for use with BHOperator
- BloodHound-customnodes: Generate JSON for POST to custom-nodes API endpoint
- BloodHound-customnode: Generate JSON for DELETE on custom-nodes API endpoint
.PARAMETER ServerInstance
Specify a specific server instance to collect from
Supported values:
- Null (default): Query the domain for SPNs and collect from each server found
- Name/FQDN: <host>
- Instance: <host>:<port|instance_name>
- SPN: <service class>/<host>:<port|instance_name>
.PARAMETER ServerListFile
Specify the path to a file containing multiple server instances to collect from in the ServerInstance formats above
.PARAMETER ServerList
Specify a comma-separated list of server instances to collect from in the ServerInstance formats above
.PARAMETER TempDir
Specify the path to a temporary directory where .json files will be stored before being zipped (default: new directory created with "[System.IO.Path]::GetTempPath()")
.PARAMETER ZipDir
Specify the path to a directory where the final .zip file will be stored (default: current directory)
.PARAMETER MemoryThresholdPercent
Stop execution when memory consumption exceeds this threshold (default: 90)
.PARAMETER Credential
Specify a PSCredential object to connect to the remote server(s):
$cred = Get-Credential
.PARAMETER UserID
Specify a login to connect to the remote server(s)
.PARAMETER SecureString
Specify a SecureString object for the login used to connect to the remote server(s):
$secureString = ConvertTo-SecureString "MyPassword123!" -AsPlainText -Force
$secureString = Read-Host "Enter password:" -AsSecureString
.PARAMETER Password
Specify a password for the login used to connect to the remote server(s)
.PARAMETER Domain
Specify a domain to use for name and SID resolution
.PARAMETER DomainEnumOnly
Switch/Flag:
- On: If SPNs are found, don’t try and perform a full MSSQL collection against each server
- Off (default): If SPNs are found, try and perform a full MSSQL collection against each server
.PARAMETER IncludeNontraversableEdges
Switch/Flag:
- On: Collect both traversable and non-traversable edges
- Off (default): Collect only traversable edges (good for offensive engagements until Pathfinding supports OpenGraph edges)
.PARAMETER MakeInterestingEdgesTraversable
Switch/Flag:
- On: Make the following edges traversable (useful for offensive engagements but prone to false positive edges that may not be abusable):
- MSSQL_HasDBScopedCred
- MSSQL_HasMappedCred
- MSSQL_HasProxyCred
- MSSQL_IsTrustedBy
- MSSQL_LinkedTo
- MSSQL_ServiceAccountFor
- Off (default): The edges above are non-traversable
.PARAMETER CollectFromLinkedServers
Switch/Flag:
- On: If linked servers are found, don’t try and perform a full MSSQL collection against each server
- Off (default): If linked servers are found, try and perform a full MSSQL collection against each server
.PARAMETER InstallADModule
Switch/Flag:
- On: Try to install the ActiveDirectory module for PowerShell if it is not already installed
- Off (default): Do not try to install the ActiveDirectory module for PowerShell if it is not already installed. Rely on DirectoryServices, ADSISearcher, DirectorySearcher, and NTAccount.Translate() for object resolution.
.PARAMETER LinkedServerTimeout
Give up enumerating linked servers after X seconds
.PARAMETER FileSizeLimit
Stop enumeration after all collected files exceed this size on disk
Supported values:
- *MB
- *GB
.PARAMETER FileSizeUpdateInterval
Receive periodic size updates as files are being written for each server (in seconds)
.PARAMETER Version
Switch/Flag:
- On: Display version information and exit
.EXAMPLE
.\MSSQLHound.ps1 -Help
Display help text
.EXAMPLE
.\MSSQLHound.ps1 -DomainEnumOnly
Enumerate SPNS in the Active Directory domain for current logon context, skipping collection from individual servers
.EXAMPLE
.\MSSQLHound.ps1 -ServerInstance
Collect data from the specified server and from any linked servers discovered
.EXAMPLE
.\MSSQLHound.ps1 -ServerInstance -CollectFromLinkedServers
Collect data from the specified server and collect from any linked servers discovered
.EXAMPLE
.\MSSQLHound.ps1
Enumerate SPNS in the Active Directory domain for current logon context, then collect data from each server with an SPN
.EXAMPLE
.\MSSQLHound.ps1 -MakeInterestingEdgesTraversable
Enumerate SPNS in the Active Directory domain for current logon context, then collect data from each server with an SPN, labelling questionably valid attack path edges traversable
.EXAMPLE
.\MSSQLHound.ps1 -IncludeNontraversableEdges
Enumerate SPNS in the Active Directory domain for current logon context, then collect data from each server with an SPN, including non-traversable edges
.LINK
https://github.com/SpecterOps/MSSQLHound
#>
[CmdletBinding()]
param(
[switch]$Help,
# Supported output formats
# - BloodHound: OpenGraph implementation
# - BHGeneric: OpenGraph implementation for use with BHOperator
# - BloodHound-customnodes: Generate JSON for POST to custom-nodes API endpoint
# - BloodHound-customnode: Generate JSON for DELETE on custom-nodes API endpoint
[ValidateSet("BloodHound", "BloodHound-customnodes", "BloodHound-customnode", "BHGeneric")]
[string]$OutputFormat = "BloodHound",
# Supported ServerInstance formats
# - Null: Query the domain for SPNs and collect from each server found
# - Name/FQDN: <host>
# - Instance: <host>:<port|instance_name>
# - SPN: <service class>/<host>:<port|instance_name>
[string]$ServerInstance,#="ps1-db.mayyhem.com",
# File containing list of servers (one per line)
[string]$ServerListFile,
# Comma-separated list of servers
[string]$ServerList,
# Validate that the temp directory exists
[ValidateScript({
if ([string]::IsNullOrEmpty($_) -or (Test-Path $_)) {
$true
} else {
throw "The specified directory does not exist: $_"
}
})]
[string]$TempDir = $null,
# Validate that the output directory exists
[ValidateScript({
if ([string]::IsNullOrEmpty($_) -or (Test-Path $_)) {
$true
} else {
throw "The specified directory does not exist: $_"
}
})]
[string]$ZipDir = $null,
# Warn user when memory consumption exceeds this threshold
[int]$MemoryThresholdPercent = 90,
# Specify SQL login credentials - useful when domain authentication isn't working
[PSCredential]$Credential,
[string]$UserID,#="lowpriv",
[SecureString]$SecureString,
[string]$Password,#="password",
# Specify domain in DOMAIN.COM format
[string]$Domain = $env:USERDNSDOMAIN,
[switch]$IncludeNontraversableEdges,
# Make the following edges traversable (prone to false positive edges that may not be abusable):
# - MSSQL_HasDBScopedCred
# - MSSQL_HasMappedCred
# - MSSQL_HasProxyCred
# - MSSQL_IsTrustedBy
# - MSSQL_LinkedTo
# - MSSQL_ServiceAccountFor
[switch]$MakeInterestingEdgesTraversable=$true,
[switch]$CollectFromLinkedServers,#=$true,
[switch]$DomainEnumOnly,#=$true,
[switch]$InstallADModule,#=$true,
[int]$LinkedServerTimeout = 300, # seconds
# File size limit to stop enumeration (e.g., "1GB", "500MB", "2.5GB")
[string]$FileSizeLimit = "1GB",
# Interval in seconds for periodic file size updates (0 to disable)
[int]$FileSizeUpdateInterval = 5,
[switch]$Version
)
# Display help text
if ($Help) {
Get-Help $MyInvocation.MyCommand.Path -Detailed
return
}
# Script version information
$script:ScriptVersion = "1.0"
$script:ScriptName = "MSSQLHound"
$script:Domain = $Domain
# Handle version request
if ($Version) {
Write-Host "$script:ScriptName version $script:ScriptVersion" -ForegroundColor Green
return
}
if ($OutputFormat -eq "BloodHound-customnodes") {
$customNodes = @{
"custom_types" = @{
"MSSQL_Database" = @{
"icon" = @{
"color" = "#f54242"
"name" = "database"
"type" = "font-awesome"
}
}
"MSSQL_ServerRole" = @{
"icon" = @{
"color" = "#6942f5"
"name" = "users-gear"
"type" = "font-awesome"
}
}
"MSSQL_Login" = @{
"icon" = @{
"color" = "#dd42f5"
"name" = "user-gear"
"type" = "font-awesome"
}
}
"MSSQL_Server" = @{
"icon" = @{
"color" = "#42b9f5"
"name" = "server"
"type" = "font-awesome"
}
}
"MSSQL_DatabaseRole" = @{
"icon" = @{
"color" = "#f5a142"
"name" = "users"
"type" = "font-awesome"
}
}
"MSSQL_DatabaseUser" = @{
"icon" = @{
"color" = "#f5ef42"
"name" = "user"
"type" = "font-awesome"
}
}
"MSSQL_ApplicationRole" = @{
"icon" = @{
"color" = "#6ff542"
"name" = "robot"
"type" = "font-awesome"
}
}
}
}
# Output the custom nodes JSON and exit
$customNodes | ConvertTo-Json -Depth 10
$customNodes | ConvertTo-Json -Depth 10 | clip.exe
# Output to clipboard
Write-Host "All custom node types JSON copied to clipboard!" -ForegroundColor Green
Write-Host "POST to /api/v2/custom-nodes (e.g., in API Explorer)" -ForegroundColor Green
return
}
elseif ($OutputFormat -eq 'BloodHound-customnode') {
# Output each custom node type as individual JSON
Write-Host "Each JSON snippet below can be sent individually to the API to delete the custom node type:`n" -ForegroundColor Cyan
Write-Output '--- MSSQL_Database ---'
@{
"custom_types" = @{
"MSSQL_Database" = @{
"icon" = @{
"color" = "#f54242"
"name" = "database"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_ServerRole ---"
@{
"custom_types" = @{
"MSSQL_ServerRole" = @{
"icon" = @{
"color" = "#6942f5"
"name" = "users-gear"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_Login ---"
@{
"custom_types" = @{
"MSSQL_Login" = @{
"icon" = @{
"color" = "#dd42f5"
"name" = "user-gear"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_Server ---"
@{
"custom_types" = @{
"MSSQL_Server" = @{
"icon" = @{
"color" = "#42b9f5"
"name" = "server"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_ApplicationRole ---"
@{
"custom_types" = @{
"MSSQL_ApplicationRole" = @{
"icon" = @{
"color" = "#6ff542"
"name" = "robot"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_DatabaseRole ---"
@{
"custom_types" = @{
"MSSQL_DatabaseRole" = @{
"icon" = @{
"color" = "#f5a142"
"name" = "users"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Output "`n--- MSSQL_DatabaseUser ---"
@{
"custom_types" = @{
"MSSQL_DatabaseUser" = @{
"icon" = @{
"color" = "#f5ef42"
"name" = "user"
"type" = "font-awesome"
}
}
}
} | ConvertTo-Json -Depth 10
Write-Host "POST to /api/v2/custom-nodes (e.g., in API Explorer)" -ForegroundColor Green
return
}
if (-not $script:Domain) {
try {
Write-Warning "No domain provided and could not find `$env:USERDNSDOMAIN, trying computer's domain"
$script:Domain = (Get-CimInstance Win32_ComputerSystem).Domain
Write-Host "Using computer's domain: $script:Domain"
} catch {
Write-Warning "Error getting computer's domain, using `$env:USERDOMAIN: $_"
$script:Domain = $env:USERDOMAIN
}
}
# Imports
# Default serializer ConvertFrom-JSON was hitting maximum size limits, so using this one instead
Add-Type -AssemblyName System.Web.Extensions
Add-Type -AssemblyName System.Data
# Add Active Directory module if needed
if (-not (Get-Module -Name ActiveDirectory)) {
if (Get-Module -ListAvailable -Name ActiveDirectory) {
Import-Module ActiveDirectory
}
}
if (-not (Get-Module -Name ActiveDirectory) -and $InstallADModule) {
Write-Host "Active Directory module not found. Attempting to install RSAT..." -ForegroundColor Yellow
# Determine OS type
$osInfo = Get-CimInstance Win32_OperatingSystem
$isServer = $osInfo.ProductType -gt 1 # 2 = Domain Controller, 3 = Server
$isClient = $osInfo.ProductType -eq 1 # 1 = Workstation (Windows 10/11)
$installSuccess = $false
if ($isServer) {
Write-Host "Detected Windows Server - trying server installation methods"
# Method 1: Standard Install-WindowsFeature
if (-not $installSuccess) {
try {
Install-WindowsFeature RSAT-AD-PowerShell -Restart:$false -ErrorAction Stop
$installSuccess = $true
Write-Host "Successfully installed RSAT using Install-WindowsFeature" -ForegroundColor Green
} catch {
Write-Host "Install-WindowsFeature failed: $_"
}
}
# Method 2: Import ServerManager first
if (-not $installSuccess) {
try {
Import-Module ServerManager -ErrorAction Stop
Install-WindowsFeature RSAT-AD-PowerShell -Restart:$false -ErrorAction Stop
$installSuccess = $true
Write-Host "Successfully installed RSAT using ServerManager module" -ForegroundColor Green
} catch {
Write-Host "ServerManager method failed: $_"
}
}
# Method 3: Try Add-WindowsFeature (older servers)
if (-not $installSuccess) {
try {
Add-WindowsFeature RSAT-AD-PowerShell -Restart:$false -ErrorAction Stop
$installSuccess = $true
Write-Host "Successfully installed RSAT using Add-WindowsFeature" -ForegroundColor Green
} catch {
Write-Host "Add-WindowsFeature failed: $_"
}
}
}
if ($isClient) {
Write-Host "Detected Windows Client - trying client installation methods"
# Method 1: Enable Windows Optional Feature (Windows 10/11)
if (-not $installSuccess) {
try {
Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell -All -NoRestart -ErrorAction Stop
$installSuccess = $true
Write-Host "Successfully installed RSAT using Windows Optional Features" -ForegroundColor Green
} catch {
Write-Host "Windows Optional Feature method failed: $_"
}
}
# Method 2: Try alternative feature name
if (-not $installSuccess) {
try {
Enable-WindowsOptionalFeature -Online -FeatureName "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0" -NoRestart -ErrorAction Stop
$installSuccess = $true
Write-Host "Successfully installed RSAT using alternative feature name" -ForegroundColor Green
} catch {
Write-Host "Alternative feature name failed: $_"
}
}
# Method 3: DISM command
if (-not $installSuccess) {
try {
$dismResult = & dism /online /enable-feature /featurename:RSATClient-Roles-AD-Powershell /all /norestart 2>&1
if ($LASTEXITCODE -eq 0) {
$installSuccess = $true
Write-Host "Successfully installed RSAT using DISM" -ForegroundColor Green
} else {
Write-Host "DISM failed with exit code: $LASTEXITCODE"
}
} catch {
Write-Host "DISM method failed: $_"
}
}
}
# Try to import the module after installation attempts
if ($installSuccess) {
Start-Sleep -Seconds 2 # Give it a moment to register
try {
Import-Module ActiveDirectory -ErrorAction Stop
Write-Host "Active Directory module successfully imported" -ForegroundColor Green
} catch {
Write-Warning "RSAT appears to be installed but module import failed: $_"
}
}
}
# Final check and warning
if (-not (Get-Module -Name ActiveDirectory)) {
Write-Warning "Could not find or install Active Directory module"
# Offer fallback methods
Write-Host "Will attempt to use .NET DirectoryServices as fallback for AD operations" -ForegroundColor Yellow
# Load .NET DirectoryServices as fallback
try {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
Add-Type -AssemblyName System.DirectoryServices
$script:UseNetFallback = $true
Write-Host "Using .NET DirectoryServices as fallback" -ForegroundColor Green
} catch {
Write-Warning "Could not load .NET DirectoryServices fallback: $_"
$script:UseNetFallback = $false
}
} else {
Write-Host "Active Directory module is available and loaded" -ForegroundColor Green
$script:UseNetFallback = $false
}
# Clear any existing script variables from previous runs
Remove-Variable -Name bloodhoundOutput -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name nodesOutput -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name edgesOutput -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name serversToProcess -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name linkedServersToProcess -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name DomainValidationCache -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name DomainResolutionCache -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name ValidatedDomainsCache -Scope Script -ErrorAction SilentlyContinue
# Initialize an object for servers specified by user or discovered during domain enumeration
$script:serversToProcess = @{}
# Initialize array for linked servers discovered during processing
$script:linkedServersToProcess = @()
# Name and SID resolution
$script:DomainValidationCache = @{}
$script:DomainResolutionCache = @{}
$script:ValidatedDomainsCache = @{}
# Initialize output structures based on format
if ($OutputFormat -eq "BloodHound") {
$script:bloodhoundOutput = @{
graph = @{
nodes = @()
edges = @()
}
}
# Track all output files for cumulative size tracking
$script:OutputFiles = @()
# Set output directory
if (-not $TempDir) {
# Create temporary directory for output files
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$tempPath = [System.IO.Path]::GetTempPath()
$TempDirectory = Join-Path $tempPath "mssql-bloodhound-$timestamp"
New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null
} else {
$TempDirectory = $TempDir
}
Write-Host "Temporary output directory: $TempDirectory" -ForegroundColor Cyan
# Initialize file size monitoring variables
$script:FileSizeLimit = $FileSizeLimit
$script:LastFileSizeCheck = Get-Date
$script:FileSizeCheckInterval = $FileSizeUpdateInterval
} elseif ($OutputFormat -eq "BHGeneric") {
$script:bloodhoundOutput = ""
$script:nodesOutput = @()
$script:edgesOutput = @()
}
# Server and Database level permissions to map
$ServerPermissionsToMap = @(
"ALTER",
"ALTER ANY LOGIN",
"ALTER ANY SERVER ROLE",
"CONTROL",
"CONNECT SQL",
"CONNECT ANY DATABASE",
"CONTROL SERVER",
"IMPERSONATE",
"IMPERSONATE ANY LOGIN",
"TAKE OWNERSHIP"
)
$DatabasePermissionsToMap = @(
"ALTER",
"ALTER ANY APPLICATION ROLE",
"ALTER ANY ROLE",
"CONNECT",
"CONTROL",
"IMPERSONATE",
"TAKE OWNERSHIP"
)
# Comprehensive predefined abusable (or non-traversable) permissions for SQL Server fixed server roles
$fixedServerRolePermissions = @{
# sysadmin implicitly has all permissions, but CONTROL SERVER trumps all, so the rest don't need to be listed
"sysadmin" = @(
#"ALTER ANY LOGIN",
#"ALTER ANY SERVER ROLE",
"CONTROL SERVER"
#"IMPERSONATE ANY LOGIN"
)
# securityadmin can manage security-related aspects and grant ANY permission to any login
"securityadmin" = @(
"ALTER ANY LOGIN"
)
# Introduced in MSSQL 2022, like securityadmin but can't grant any permission to any login
"##MS_LoginManager##" = @(
"ALTER ANY LOGIN"
)
# Introduced in MSSQL 2022, allows server principal CONNECT permission on all databases without a mapping to a database user
"##MS_DatabaseConnector##" = @(
"CONNECT ANY DATABASE"
)
# public has minimal permissions
"public" = @()
}
# Comprehensive predefined permissions for SQL Server fixed database roles
$fixedDatabaseRolePermissions = @{
# db_owner has all permissions, CONTROL encompasses them
"db_owner" = @(
#"ALTER ANY APPLICATION ROLE",
#"ALTER ANY ROLE",
"CONTROL"
)
# db_securityadmin can manage roles and users
"db_securityadmin" = @(
"ALTER ANY APPLICATION ROLE",
"ALTER ANY ROLE"
)
# db_accessadmin can manage database access
"db_accessadmin" = @(
)
# db_backupoperator can back up the database
"db_backupoperator" = @(
)
# db_ddladmin can run DDL commands
"db_ddladmin" = @(
)
# db_datawriter can modify data
"db_datawriter" = @(
)
# db_datareader can read all data
"db_datareader" = @(
)
# db_denydatawriter cannot modify data
"db_denydatawriter" = @(
# DELETE, INSERT, and UPDATE are explicitly denied
)
# db_denydatareader cannot read data
"db_denydatareader" = @(
# SELECT is explicitly denied
)
# public has minimal permissions
"public" = @(
#"CONNECT"
)
}
# Helper function to display current file size
function Show-CurrentFileSize {
param(
[Parameter(Mandatory=$true)]
[PSObject]$WriterObj,
[string]$Context = ""
)
try {
# Calculate cumulative size of completed files only
$cumulativeSize = 0
$fileCount = $script:OutputFiles.Count
foreach ($file in $script:OutputFiles) {
if (Test-Path $file) {
$fileInfo = Get-Item $file
$cumulativeSize += $fileInfo.Length
}
}
# Get current file size (not included in cumulative)
$currentFileSize = 0
if (Test-Path $WriterObj.FilePath) {
$fileInfo = Get-Item $WriterObj.FilePath
$currentFileSize = $fileInfo.Length
# Format current file size for display
$currentSizeDisplay = if ($currentFileSize -ge 1GB) {
"$([math]::Round($currentFileSize/1GB, 2)) GB"
} elseif ($currentFileSize -ge 1MB) {
"$([math]::Round($currentFileSize/1MB, 2)) MB"
} elseif ($currentFileSize -ge 1KB) {
"$([math]::Round($currentFileSize/1KB, 2)) KB"
} else {
"$currentFileSize bytes"
}
}
# Format cumulative size (completed files only)
$sizeDisplay = if ($cumulativeSize -ge 1GB) {
"$([math]::Round($cumulativeSize/1GB, 2)) GB"
} elseif ($cumulativeSize -ge 1MB) {
"$([math]::Round($cumulativeSize/1MB, 2)) MB"
} elseif ($cumulativeSize -ge 1KB) {
"$([math]::Round($cumulativeSize/1KB, 2)) KB"
} else {
"$cumulativeSize bytes"
}
$contextText = if ($Context) { " ($Context)" } else { "" }
# Show current file and cumulative of completed files
if ($fileCount -gt 0) {
Write-Host "Current file size: $currentSizeDisplay`nCumulative file size: $sizeDisplay across $fileCount files$contextText" -ForegroundColor Cyan
} else {
Write-Host "Current file size: $currentSizeDisplay" -ForegroundColor Cyan
}
}
catch {
# Silently continue if there's an error checking file size
}
}
# Helper function to check if enough time has passed for periodic update
function Test-ShouldShowPeriodicUpdate {
$currentTime = Get-Date
$timeSinceLastCheck = ($currentTime - $script:LastFileSizeCheck).TotalSeconds
if ($timeSinceLastCheck -ge $script:FileSizeCheckInterval) {
$script:LastFileSizeCheck = $currentTime
return $true
}
return $false
}
# Helper function to check file size
function Test-FileSizeLimit {
param(
[Parameter(Mandatory=$true)]
[PSObject]$WriterObj,
[string]$SizeLimitString = "1GB"
)
# If we're already stopping, just return true without additional warnings
if ($script:stopProcessing) {
return $true
}
try {
# Parse the size limit string
$SizeLimitBytes = 0
if ($SizeLimitString -match '^(\d+\.?\d*)\s*(GB|MB|KB|B)?$') {
$value = [double]$matches[1]
$unit = $matches[2]
switch ($unit) {
"GB" { $SizeLimitBytes = $value * 1GB }
"MB" { $SizeLimitBytes = $value * 1MB }
"KB" { $SizeLimitBytes = $value * 1KB }
"B" { $SizeLimitBytes = $value }
default { $SizeLimitBytes = $value * 1GB } # Default to GB if no unit
}
} else {
Write-Warning "Invalid file size limit format: '$SizeLimitString'. Using default 1GB."
$SizeLimitBytes = 1GB
}
# Calculate cumulative size of all completed files
$cumulativeSize = 0
foreach ($file in $script:OutputFiles) {
if (Test-Path $file) {
$fileInfo = Get-Item $file
$cumulativeSize += $fileInfo.Length
}
}
# Add current file being written
if ($WriterObj.FilePath -and (Test-Path $WriterObj.FilePath)) {
$currentFileInfo = Get-Item $WriterObj.FilePath
$cumulativeSize += $currentFileInfo.Length
}
if ($cumulativeSize -ge $SizeLimitBytes) {
$totalFiles = $script:OutputFiles.Count
if ($WriterObj.FilePath -and (Test-Path $WriterObj.FilePath)) {
$totalFiles++ # Include current file in count
}
Write-Warning "Cumulative file size limit reached: $([math]::Round($cumulativeSize/1MB, 2)) MB >= $SizeLimitString"
Write-Warning "Total files: $totalFiles ($(($script:OutputFiles.Count)) completed + 1 in progress)"
return $true
}
return $false
}
catch {
Write-Warning "Error checking file size: $_"
return $false
}
}
# Memory monitoring function
function Test-MemoryUsage {
param(
[int]$Threshold = 80
)
$os = Get-WmiObject Win32_OperatingSystem
$memoryUsedGB = ($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / 1MB
$totalMemoryGB = $os.TotalVisibleMemorySize / 1MB
$percentUsed = ($memoryUsedGB / $totalMemoryGB) * 100
Write-Host "Memory usage: $([math]::Round($percentUsed, 2))% ($([math]::Round($memoryUsedGB, 2))GB / $([math]::Round($totalMemoryGB, 2))GB)" -ForegroundColor Cyan
if ($percentUsed -gt $Threshold) {
Write-Warning "Memory usage is at $([math]::Round($percentUsed, 2))%. Threshold: $Threshold%"
return $false
}
return $true
}
# Create constructor functions for streaming writers
function New-BaseStreamingWriter {
param(
[string]$FilePath,
[string]$WriterType = "Base"
)
# Store the absolute path - ensure it's relative to current directory
if ([System.IO.Path]::IsPathRooted($FilePath)) {
$absolutePath = $FilePath
} else {
# Use PowerShell's current location for relative paths
$absolutePath = Join-Path (Get-Location).Path $FilePath
}
try {
# Ensure directory exists
$directory = [System.IO.Path]::GetDirectoryName($absolutePath)
if ($directory -and -not [System.IO.Directory]::Exists($directory)) {
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
}
# Create the file with explicit encoding
$writer = New-Object System.IO.StreamWriter($absolutePath, $false, [System.Text.Encoding]::UTF8)
$writer.AutoFlush = $true
# Verify file was created
if (Test-Path $absolutePath) {
Write-Host "Created output file: $absolutePath" -ForegroundColor Cyan
} else {
throw "File was not created at: $absolutePath"
}
# Return writer object with metadata
$writerObj = New-Object PSObject -Property @{
Writer = $writer
FilePath = $absolutePath
ItemCount = 0
WriterType = $WriterType
}
return $writerObj
}
catch {
Write-Error "Failed to create output file '$absolutePath': $_"
throw
}
}
function Close-StreamingWriter {
param(
[Parameter(Mandatory=$true)]
[PSObject]$WriterObj
)
try {
if ($WriterObj.Writer) {
$WriterObj.Writer.Flush()
$WriterObj.Writer.Close()
$WriterObj.Writer.Dispose()
$WriterObj.Writer = $null
# Small delay to ensure file system has caught up
Start-Sleep -Milliseconds 100
# Verify file exists and has content
if (Test-Path $WriterObj.FilePath) {
$fileInfo = Get-Item $WriterObj.FilePath
Write-Host "Output written to $($WriterObj.FilePath)" -ForegroundColor Green
# Convert bytes to appropriate unit
$fileSize = $fileInfo.Length
if ($fileSize -ge 1MB) {
Write-Host "File size: $([math]::Round($fileSize/1MB, 2)) MB" -ForegroundColor Cyan
} elseif ($fileSize -ge 1KB) {
Write-Host "File size: $([math]::Round($fileSize/1KB, 2)) KB" -ForegroundColor Cyan
} else {
Write-Host "File size: $fileSize bytes" -ForegroundColor Cyan
}
} else {
Write-Error "File was not found after closing: $($WriterObj.FilePath)"
}
}
}
catch {
Write-Error "Error closing file: $_"
Write-Error $_.Exception.StackTrace
}
}
# JSON Writer Functions
function New-StreamingJsonWriter {
param(
[string]$FilePath