forked from SpecterOps/MSSQLHound
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInvoke-MSSQLHoundUnitTests.ps1
More file actions
8692 lines (7404 loc) · 350 KB
/
Invoke-MSSQLHoundUnitTests.ps1
File metadata and controls
8692 lines (7404 loc) · 350 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
# PowerShell MSSQL Collector Unit Test Kit for BloodHound OpenGraph
# by Chris Thompson (@_Mayyhem) at SpecterOps
#
# Required Permissions:
# - MSSQL sysadmin server role
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$ServerInstance="ps1-db.mayyhem.com",
[Parameter(Mandatory=$false)]
[string]$EnumerationScript = ".\MSSQLHound.ps1",
[Parameter(Mandatory=$false)]
[string]$Domain = $env:USERDOMAIN,
[Parameter(Mandatory=$false)]
[ValidateSet("All", "Setup", "Test", "Coverage", "Report", "Teardown", "MissingTests")]
[string]$Action = "All",
[Parameter(Mandatory=$false)]
[ValidateSet("offensive", "defensive", "both")]
[string]$Perspective = "offensive",
# Credentials used to create test objects -- must be sysadmin
[Parameter(Mandatory=$false)]
[string]$UserID,#="test",
[Parameter(Mandatory=$false)]
[string]$Password,#="password",
[Parameter(Mandatory=$false)]
[string]$LogFile = $null,
[Parameter(Mandatory=$false)]
[string]$LimitToEdge = "",
[switch]$SkipCreateDomainUsers,
[switch]$SkipDomainObjects,
[switch]$SkipHTMLReport,
[Parameter(Mandatory=$false)]
[switch]$ShowDebugOutput
)
# Save debug flag at script level
$script:ShowDebugOutput = $ShowDebugOutput
# Script-wide variables
$script:TestResults = @{
Timestamp = Get-Date
ServerInstance = $ServerInstance
Domain = $Domain
SetupSuccess = $false
TestRuns = @()
Coverage = @{}
}
# Define edge types by perspective
# Edges with test coverage have a # after the edge name
$script:OffensiveOnlyEdges = @(
"MSSQL_AddMember", #
"MSSQL_Alter", #
"MSSQL_ChangeOwner", #
"MSSQL_ChangePassword", #
"MSSQL_Control", #
"MSSQL_ExecuteAs", #
"MSSQL_Impersonate" #
)
$script:DefensiveOnlyEdges = @(
"MSSQL_AlterDB",
"MSSQL_AlterDBRole",
"MSSQL_AlterServerRole",
"MSSQL_ControlDBRole",
"MSSQL_ControlDBUser",
"MSSQL_ControlLogin",
"MSSQL_ControlServerRole",
"MSSQL_DBTakeOwnership",
"MSSQL_ImpersonateDBUser",
"MSSQL_ImpersonateLogin"
)
$script:BothPerspectivesEdges = @(
"CoerceAndRelayToMSSQL", #
"HasSession", #
"MSSQL_AlterAnyAppRole", #
"MSSQL_AlterAnyDBRole", #
"MSSQL_AlterAnyLogin", #
"MSSQL_AlterAnyServerRole", #
"MSSQL_Connect", #
"MSSQL_ConnectAnyDatabase", #
"MSSQL_Contains", #
"MSSQL_ControlDB", #
"MSSQL_ControlServer", #
"MSSQL_ExecuteAsOwner", #
"MSSQL_ExecuteOnHost", #
"MSSQL_GetAdminTGS", #
"MSSQL_GetTGS", #
"MSSQL_GrantAnyDBPermission", #
"MSSQL_GrantAnyPermission", #
"MSSQL_HasDBScopedCred", #
"MSSQL_HasLogin", #
"MSSQL_HasMappedCred", #
"MSSQL_HasProxyCred", #
"MSSQL_HostFor", #
"MSSQL_ImpersonateAnyLogin", #
"MSSQL_IsMappedTo", #
"MSSQL_IsTrustedBy", #
"MSSQL_LinkedAsAdmin", #
"MSSQL_LinkedTo", #
"MSSQL_MemberOf", #
"MSSQL_Owns", #
"MSSQL_ServiceAccountFor", #
"MSSQL_TakeOwnership" #
)
# Combine all edge types
$script:AllEdgeTypes = $script:OffensiveOnlyEdges + $script:DefensiveOnlyEdges + $script:BothPerspectivesEdges | Sort-Object
$script:CleanupSQL = @'
USE master;
GO
-- First, kill all connections to EdgeTest databases
DECLARE @kill NVARCHAR(MAX);
SET @kill = '';
DECLARE @sql NVARCHAR(MAX);
-- Get SQL Server version
DECLARE @version INT;
SET @version = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT);
-- Build the kill command dynamically based on version
IF @version >= 10 -- SQL Server 2008 and later
BEGIN
SET @sql = '
SELECT @killList = @killList + ''KILL '' + CAST(session_id AS VARCHAR(10)) + ''; ''
FROM sys.dm_exec_sessions
WHERE database_id IN (SELECT database_id FROM sys.databases WHERE name LIKE ''EdgeTest_%'' OR name LIKE ''ExecuteAsOwnerTest_%'')';
EXEC sp_executesql @sql, N'@killList NVARCHAR(MAX) OUTPUT', @killList = @kill OUTPUT;
END
ELSE -- SQL Server 2005
BEGIN
SELECT @kill = @kill + 'KILL ' + CAST(spid AS VARCHAR(10)) + '; '
FROM sys.sysprocesses
WHERE dbid IN (SELECT dbid FROM sys.sysdatabases WHERE name LIKE 'EdgeTest_%' OR name LIKE 'ExecuteAsOwnerTest_%');
END
IF @kill != ''
BEGIN
BEGIN TRY
EXEC(@kill);
END TRY
BEGIN CATCH
PRINT 'Some connections could not be killed';
END CATCH
END
GO
-- Drop all test databases first (this resolves login ownership issues)
DECLARE @sql NVARCHAR(MAX);
SET @sql = '';
SELECT @sql = @sql +
'IF EXISTS (SELECT * FROM sys.databases WHERE name = ''' + name + ''')
BEGIN
ALTER DATABASE [' + name + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [' + name + '];
END
'
FROM sys.databases
WHERE name LIKE 'EdgeTest_%' OR name LIKE 'ExecuteAsOwnerTest_%';
IF @sql != ''
BEGIN
EXEC sp_executesql @sql;
END
GO
-- Remove all role members before dropping roles
DECLARE @roleName NVARCHAR(128);
DECLARE @memberName NVARCHAR(128);
DECLARE @sql2 NVARCHAR(MAX);
DECLARE @memberCursorSQL NVARCHAR(MAX);
-- Check SQL Server version for is_fixed_role support
DECLARE @version2 INT;
SET @version2 = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT);
IF @version2 >= 11 -- SQL Server 2012+
BEGIN
SET @memberCursorSQL = '
DECLARE role_member_cursor CURSOR FOR
SELECT r.name as RoleName, p.name as MemberName
FROM sys.server_role_members rm
JOIN sys.server_principals r ON rm.role_principal_id = r.principal_id
JOIN sys.server_principals p ON rm.member_principal_id = p.principal_id
WHERE r.type = ''R''
AND r.is_fixed_role = 0
AND r.name LIKE ''%Test_%'';';
END
ELSE -- SQL Server 2005-2008 R2
BEGIN
SET @memberCursorSQL = '
DECLARE role_member_cursor CURSOR FOR
SELECT r.name as RoleName, p.name as MemberName
FROM sys.server_role_members rm
JOIN sys.server_principals r ON rm.role_principal_id = r.principal_id
JOIN sys.server_principals p ON rm.member_principal_id = p.principal_id
WHERE r.type = ''R''
AND r.name NOT IN (''sysadmin'', ''securityadmin'', ''serveradmin'', ''setupadmin'', ''processadmin'', ''diskadmin'', ''dbcreator'', ''bulkadmin'', ''public'')
AND r.name LIKE ''%Test_%'';';
END
EXEC sp_executesql @memberCursorSQL;
OPEN role_member_cursor;
FETCH NEXT FROM role_member_cursor INTO @roleName, @memberName;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
SET @sql2 = 'ALTER SERVER ROLE [' + @roleName + '] DROP MEMBER [' + @memberName + ']';
EXEC(@sql2);
PRINT 'Removed ' + @memberName + ' from role ' + @roleName;
END TRY
BEGIN CATCH
PRINT 'Could not remove member from role: ' + ERROR_MESSAGE();
END CATCH
FETCH NEXT FROM role_member_cursor INTO @roleName, @memberName;
END
CLOSE role_member_cursor;
DEALLOCATE role_member_cursor;
GO
-- Now drop all test server roles
DECLARE @roleName2 NVARCHAR(128);
DECLARE @roleCursorSQL NVARCHAR(MAX);
DECLARE @version3 INT;
SET @version3 = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT);
IF @version3 >= 11 -- SQL Server 2012+
BEGIN
SET @roleCursorSQL = '
DECLARE role_cursor CURSOR FOR
SELECT name FROM sys.server_principals
WHERE type = ''R''
AND is_fixed_role = 0
AND name LIKE ''%Test_%'';';
END
ELSE -- SQL Server 2005-2008 R2
BEGIN
SET @roleCursorSQL = '
DECLARE role_cursor CURSOR FOR
SELECT name FROM sys.server_principals
WHERE type = ''R''
AND name NOT IN (''sysadmin'', ''securityadmin'', ''serveradmin'', ''setupadmin'', ''processadmin'', ''diskadmin'', ''dbcreator'', ''bulkadmin'', ''public'')
AND name LIKE ''%Test_%'';';
END
EXEC sp_executesql @roleCursorSQL;
OPEN role_cursor;
FETCH NEXT FROM role_cursor INTO @roleName2;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC('DROP SERVER ROLE [' + @roleName2 + ']');
PRINT 'Dropped server role: ' + @roleName2;
END TRY
BEGIN CATCH
PRINT 'Could not drop server role: ' + @roleName2 + ' - ' + ERROR_MESSAGE();
END CATCH
FETCH NEXT FROM role_cursor INTO @roleName2;
END
CLOSE role_cursor;
DEALLOCATE role_cursor;
GO
-- Drop all test logins
DECLARE @loginName NVARCHAR(128);
DECLARE login_cursor CURSOR FOR
SELECT name FROM sys.server_principals
WHERE type IN ('S', 'U', 'G')
AND name LIKE '%Test%';
OPEN login_cursor;
FETCH NEXT FROM login_cursor INTO @loginName;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC('DROP LOGIN [' + @loginName + ']');
PRINT 'Dropped login: ' + @loginName;
END TRY
BEGIN CATCH
PRINT 'Could not drop login: ' + @loginName + ' - ' + ERROR_MESSAGE();
END CATCH
FETCH NEXT FROM login_cursor INTO @loginName;
END
CLOSE login_cursor;
DEALLOCATE login_cursor;
GO
-- Drop credentials
IF EXISTS (SELECT * FROM sys.credentials WHERE name LIKE 'EdgeTest_%')
BEGIN
DECLARE @credName NVARCHAR(128);
DECLARE cred_cursor CURSOR FOR
SELECT name FROM sys.credentials WHERE name LIKE 'EdgeTest_%';
OPEN cred_cursor;
FETCH NEXT FROM cred_cursor INTO @credName;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC('DROP CREDENTIAL [' + @credName + ']');
PRINT 'Dropped credential: ' + @credName;
END TRY
BEGIN CATCH
PRINT 'Could not drop credential: ' + @credName;
END CATCH
FETCH NEXT FROM cred_cursor INTO @credName;
END
CLOSE cred_cursor;
DEALLOCATE cred_cursor;
END
GO
-- Drop linked servers
IF EXISTS (SELECT * FROM sys.servers WHERE is_linked = 1 AND name LIKE '%Test%')
BEGIN
DECLARE @linkedName NVARCHAR(128);
DECLARE linked_cursor CURSOR FOR
SELECT name FROM sys.servers WHERE is_linked = 1 AND name LIKE '%Test%';
OPEN linked_cursor;
FETCH NEXT FROM linked_cursor INTO @linkedName;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC sp_dropserver @linkedName, 'droplogins';
PRINT 'Dropped linked server: ' + @linkedName;
END TRY
BEGIN CATCH
PRINT 'Could not drop linked server: ' + @linkedName;
END CATCH
FETCH NEXT FROM linked_cursor INTO @linkedName;
END
CLOSE linked_cursor;
DEALLOCATE linked_cursor;
END
GO
PRINT 'Cleanup completed';
'@
#region Helper Functions
function Write-TestLog {
param(
[string]$Message,
[ValidateSet("Info", "Success", "Warning", "Error", "Test", "Debug")]
[string]$Level = "Info"
)
$color = switch ($Level) {
"Info" { "White" }
"Success" { "Green" }
"Warning" { "Yellow" }
"Error" { "Red" }
"Test" { "Cyan" }
"Debug" { "Magenta" }
}
$prefix = switch ($Level) {
"Info" { "[INFO]" }
"Success" { "[$([char]0x2713)]" }
"Warning" { "[!]" }
"Error" { "[$([char]0x2717)]" }
"Test" { "[TEST]" }
"Debug" { "[DEBUG]" }
}
# Skip empty messages and single "=" characters
if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "=") {
return
}
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "$timestamp $prefix $Message"
# Write to console
Write-Host "$prefix $Message" -ForegroundColor $color
# Write to log file if specified
if ($script:LogFile) {
$logMessage | Out-File -FilePath $script:LogFile -Append -Encoding UTF8
}
}
# Helper function to extract and read MSSQL output from ZIP
function Get-MSSQLOutputFromZip {
param(
[string]$ZipPattern = "mssql-bloodhound-*.zip"
)
# Find the most recent ZIP file
$zipFiles = Get-ChildItem -Path . -Filter $ZipPattern | Sort-Object LastWriteTime -Descending
if (-not $zipFiles) {
return $null
}
$zipFile = $zipFiles[0]
Write-TestLog "Found ZIP file: $($zipFile.FullName)" -Level Info
# Create temp directory for extraction
$tempDir = Join-Path $env:TEMP "MSSQLEnum_$(Get-Date -Format 'yyyyMMddHHmmss')"
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
try {
# Extract ZIP
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipFile.FullName, $tempDir)
# Find all JSON files in the extracted content
$jsonFiles = Get-ChildItem -Path $tempDir -Filter "*.json" -Recurse
Write-TestLog "Found $($jsonFiles.Count) JSON files in ZIP" -Level Info
# Combine all nodes and edges from all files
$combinedOutput = @{
graph = @{
nodes = @()
edges = @()
}
}
foreach ($jsonFile in $jsonFiles) {
Write-TestLog "Reading JSON from: $($jsonFile.Name)" -Level Info
$content = Get-Content $jsonFile.FullName -Raw | ConvertFrom-Json
# Add nodes and edges to combined output
if ($content.graph) {
if ($content.graph.nodes) {
$combinedOutput.graph.nodes += $content.graph.nodes
}
if ($content.graph.edges) {
$combinedOutput.graph.edges += $content.graph.edges
}
}
}
Write-TestLog "Combined output: $($combinedOutput.graph.nodes.Count) nodes, $($combinedOutput.graph.edges.Count) edges" -Level Info
# Clean up temp directory
Remove-Item $tempDir -Recurse -Force
# Clean up ZIP file
Remove-Item $zipFile.FullName -Force
Write-TestLog "Cleaned up ZIP file: $($zipFile.Name)" -Level Info
return $combinedOutput
}
catch {
Write-TestLog "Error extracting ZIP: $_" -Level Error
if (Test-Path $tempDir) {
Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
return $null
}
# SQL execution function
function Invoke-TestSQL {
param(
[string]$ServerInstance,
[string]$Query,
[int]$QueryTimeout = 30
)
$connection = New-Object System.Data.SqlClient.SqlConnection
# Create a connection to SQL Server
$connectionString = "Server=${ServerInstance};Database=master"
if ($UserID -and $Password) {
$connectionString += ";User ID=$UserID;Password=$Password"
} else {
$connectionString += ";Integrated Security=True"
}
$connection.ConnectionString = $connectionString
# Capture SQL messages and errors
$messages = @()
$errorMessages = @()
# Event handlers for SQL messages
$connection.add_InfoMessage({
param($sender, $e)
$messages += $e.Message
Write-Verbose "SQL Info: $($e.Message)"
})
try {
$connection.Open()
# Split by GO statements
$queries = $Query -split '(?:\r?\n|^)\s*GO\s*(?:\r?\n|$)'
Write-Verbose "Split into $($queries.Count) batches"
if ($ShowDebugOutput) {
# Debug: Show all batches
for ($i = 0; $i -lt $queries.Count; $i++) {
$trimmed = $queries[$i].Trim()
if ($trimmed.Length -gt 0) {
$firstLine = ($trimmed -split "`n")[0].Trim()
if ($firstLine.Length -gt 80) {
$firstLine = $firstLine.Substring(0, 80) + "..."
}
Write-TestLog "Batch $($i+1)/$($queries.Count) (length: $($queries[$i].Length)): $firstLine" -Level Debug
} else {
Write-TestLog "Batch $($i+1)/$($queries.Count) (length: 0): [EMPTY]" -Level Debug
}
}
}
foreach ($q in $queries) {
if ([string]::IsNullOrWhiteSpace($q)) {
Write-Verbose "Skipping empty batch"
continue
}
# Show which part we're executing
$trimmedQ = $q.Trim()
$firstLine = ($trimmedQ -split "`n")[0].Trim()
if ($firstLine.Length -gt 100) {
$firstLine = $firstLine.Substring(0, 100) + "..."
}
if ($ShowDebugOutput) {
Write-TestLog "Executing batch with length $($q.Length): $firstLine" -Level Debug
}
# Handle USE statements - but don't skip the rest of the batch!
if ($q -match '^\s*USE\s+\[?(\w+)\]?\s*;?\s*(.*)$' -and $matches[1]) {
$dbName = $matches[1]
$remainingSQL = $matches[2]
try {
$connection.ChangeDatabase($dbName)
Write-Verbose "Changed to database: $dbName"
# If there's more SQL after the USE statement, execute it
if ($remainingSQL -and $remainingSQL.Trim().Length -gt 0) {
if ($ShowDebugOutput) {
Write-TestLog "Executing remaining SQL after USE statement (length: $($remainingSQL.Length))" -Level Debug
}
$q = $remainingSQL
# Don't continue - let it fall through to execute the remaining SQL
} else {
# Only USE statement, nothing else
continue
}
}
catch {
Write-Error "Failed to change to database '$dbName': $_"
throw
}
}
try {
$command = $connection.CreateCommand()
$command.CommandText = $q
$command.CommandTimeout = $QueryTimeout
# Determine if this is a SELECT query or not
$trimmedQuery = $q.Trim()
if ($trimmedQuery -match '^\s*SELECT' -and $trimmedQuery -notmatch '^\s*SELECT\s+@') {
# Use ExecuteReader for SELECT queries
$reader = $command.ExecuteReader()
while ($reader.Read()) { }
$reader.Close()
} else {
# Use ExecuteNonQuery for DDL/DML statements
$result = $command.ExecuteNonQuery()
if ($ShowDebugOutput) {
Write-TestLog "ExecuteNonQuery returned: $result" -Level Debug
Write-TestLog "Query affected $result rows" -Level Debug
}
}
Write-Verbose "Query executed successfully"
}
catch {
$errorMessages += $_.Exception.Message
Write-Error "SQL Error at line: $($_.Exception.LineNumber)`nMessage: $($_.Exception.Message)`nQuery: $preview"
# Don't throw - continue to next batch to see all errors
# throw
}
}
}
catch {
Write-Error "Connection Error: $_"
throw
}
finally {
if ($connection.State -eq 'Open') {
$connection.Close()
}
}
# Report all collected errors
if ($errorMessages.Count -gt 0) {
Write-Error "SQL Execution completed with $($errorMessages.Count) errors:"
foreach ($err in $errorMessages) {
Write-Error " - $err"
}
throw "SQL script failed with errors: $($errorMessages -join '; ')"
}
}
# Add Active Directory module if needed
if (-not (Get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue)) {
if (Get-Module -ListAvailable -Name ActiveDirectory -ErrorAction SilentlyContinue) {
Import-Module ActiveDirectory
}
}
function Test-DomainUser {
param([string]$Username)
try {
$searcher = [adsisearcher]"(&(objectClass=user)(samAccountName=$Username))"
$searcher.SearchRoot = [adsi]"LDAP://$Domain"
$result = $searcher.FindOne()
return ($null -ne $result)
}
catch {
return $false
}
}
function New-DomainTestUser {
param(
[string]$Username,
[string]$Password = "TestP@ssw0rd123!"
)
if ($SkipDomainObjects) {
Write-TestLog "Skipping domain user creation (SkipDomainObjects flag set)" -Level Warning
return $false
}
try {
# Check if we have domain admin rights
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($currentUser)
if (-not $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-TestLog "Not running as administrator - cannot create domain users" -Level Warning
return $false
}
# Try to create user in AD
if (Get-Command New-ADUser -ErrorAction SilentlyContinue) {
if (-not (Test-DomainUser -Username $Username)) {
New-ADUser -Name $Username `
-SamAccountName $Username `
-UserPrincipalName "$Username@$Domain" `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $true `
-PasswordNeverExpires $true `
-CannotChangePassword $true
Write-TestLog "Created domain user: $Domain\$Username" -Level Success
return $true
}
else {
Write-TestLog "Domain user already exists: $Domain\$Username" -Level Warning
return $true
}
}
else {
Write-TestLog "AD PowerShell module not available" -Level Warning
return $false
}
}
catch {
Write-TestLog "Failed to create domain user $Username : $_" -Level Warning
return $false
}
}
#endregion
#region Setup Functions
# Define setup SQL for MSSQL_AddMember
$script:SetupSQL_AddMember = @'
USE master;
GO
-- =====================================================
-- COMPLETE SETUP FOR MSSQL_AddMember EDGE TESTING
-- =====================================================
-- This creates all objects needed to test every source/target
-- combination for MSSQL_AddMember edges
-- Note: Principals cannot be assigned ALTER/CONTROL on a fixed server role or database role
-- Create test database if it doesn't exist
CREATE DATABASE [EdgeTest_AddMember];
GO
-- =====================================================
-- SERVER LEVEL: Login -> ServerRole
-- =====================================================
-- Login with ALTER permission on user-defined server role
CREATE LOGIN [AddMemberTest_Login_CanAlterServerRole] WITH PASSWORD = 'EdgeTestP@ss123!';
CREATE SERVER ROLE [AddMemberTest_ServerRole_TargetOf_Login_CanAlterServerRole];
GRANT ALTER ON SERVER ROLE::[AddMemberTest_ServerRole_TargetOf_Login_CanAlterServerRole] TO [AddMemberTest_Login_CanAlterServerRole];
-- Login with CONTROL permission on user-defined server role
CREATE LOGIN [AddMemberTest_Login_CanControlServerRole] WITH PASSWORD = 'EdgeTestP@ss123!';
CREATE SERVER ROLE [AddMemberTest_ServerRole_TargetOf_Login_CanControlServerRole];
GRANT CONTROL ON SERVER ROLE::[AddMemberTest_ServerRole_TargetOf_Login_CanControlServerRole] TO [AddMemberTest_Login_CanControlServerRole];
-- Login with ALTER ANY SERVER ROLE permission can add to any user-defined role
CREATE LOGIN [AddMemberTest_Login_CanAlterAnyServerRole] WITH PASSWORD = 'EdgeTestP@ss123!';
GRANT ALTER ANY SERVER ROLE TO [AddMemberTest_Login_CanAlterAnyServerRole];
-- Login with ALTER ANY SERVER ROLE and member of fixed role can add to that fixed role
ALTER SERVER ROLE [processadmin] ADD MEMBER [AddMemberTest_Login_CanAlterAnyServerRole];
-- Login with ALTER ANY SERVER ROLE cannot add to sysadmin even as member (negative test)
ALTER SERVER ROLE [sysadmin] ADD MEMBER [AddMemberTest_Login_CanAlterAnyServerRole];
-- Even though member of sysadmin, cannot add members to sysadmin role
-- =====================================================
-- SERVER LEVEL: ServerRole -> ServerRole
-- =====================================================
-- Server role with ALTER permission on user-defined role
CREATE SERVER ROLE [AddMemberTest_ServerRole_CanAlterServerRole];
CREATE SERVER ROLE [AddMemberTest_ServerRole_TargetOf_ServerRole_CanAlterServerRole];
GRANT ALTER ON SERVER ROLE::[AddMemberTest_ServerRole_TargetOf_ServerRole_CanAlterServerRole] TO [AddMemberTest_ServerRole_CanAlterServerRole];
-- Server role with CONTROL permission on user-defined role
CREATE SERVER ROLE [AddMemberTest_ServerRole_CanControlServerRole];
CREATE SERVER ROLE [AddMemberTest_ServerRole_TargetOf_ServerRole_CanControlServerRole];
GRANT CONTROL ON SERVER ROLE::[AddMemberTest_ServerRole_TargetOf_ServerRole_CanControlServerRole] TO [AddMemberTest_ServerRole_CanControlServerRole];
-- Server role with ALTER ANY SERVER ROLE can add to any user-defined role
CREATE SERVER ROLE [AddMemberTest_ServerRole_CanAlterAnyServerRole];
GRANT ALTER ANY SERVER ROLE TO [AddMemberTest_ServerRole_CanAlterAnyServerRole];
-- Server role with ALTER ANY SERVER ROLE and member of fixed role can add to that fixed role
ALTER SERVER ROLE [processadmin] ADD MEMBER [AddMemberTest_ServerRole_CanAlterAnyServerRole];
-- =====================================================
-- DATABASE LEVEL SETUP
-- =====================================================
USE [EdgeTest_AddMember];
GO
-- =====================================================
-- DATABASE LEVEL: DatabaseUser -> DatabaseRole
-- =====================================================
-- Database user with ALTER on user-defined role
CREATE USER [AddMemberTest_User_CanAlterDbRole] WITHOUT LOGIN;
CREATE ROLE [AddMemberTest_DbRole_TargetOf_User_CanAlterDbRole];
GRANT ALTER ON ROLE::[AddMemberTest_DbRole_TargetOf_User_CanAlterDbRole] TO [AddMemberTest_User_CanAlterDbRole];
-- Database user with CONTROL on user-defined role
CREATE USER [AddMemberTest_User_CanControlDbRole] WITHOUT LOGIN;
CREATE ROLE [AddMemberTest_DbRole_TargetOf_User_CanControlDbRole];
GRANT CONTROL ON ROLE::[AddMemberTest_DbRole_TargetOf_User_CanControlDbRole] TO [AddMemberTest_User_CanControlDbRole];
-- Database user with ALTER ANY ROLE can add to any user-defined role
CREATE USER [AddMemberTest_User_CanAlterAnyDbRole] WITHOUT LOGIN;
GRANT ALTER ANY ROLE TO [AddMemberTest_User_CanAlterAnyDbRole];
-- Database user with ALTER on database (grants ALTER ANY ROLE) can add to user-defined roles
CREATE USER [AddMemberTest_User_CanAlterDb] WITHOUT LOGIN;
GRANT ALTER ON DATABASE::[EdgeTest_AddMember] TO [AddMemberTest_User_CanAlterDb];
-- Create target roles for principals with ALTER on database
CREATE ROLE [AddMemberTest_DbRole_TargetOf_User_CanAlterDb];
CREATE ROLE [AddMemberTest_DbRole_TargetOf_DbRole_CanAlterDb];
CREATE ROLE [AddMemberTest_DbRole_TargetOf_AppRole_CanAlterDb];
-- =====================================================
-- DATABASE LEVEL: DatabaseRole -> DatabaseRole
-- =====================================================
-- Database role with ALTER on a user-defined role
CREATE ROLE [AddMemberTest_DbRole_CanAlterDbRole];
CREATE ROLE [AddMemberTest_DbRole_TargetOf_DbRole_CanAlterDbRole];
GRANT ALTER ON ROLE::[AddMemberTest_DbRole_TargetOf_DbRole_CanAlterDbRole] TO [AddMemberTest_DbRole_CanAlterDbRole];
-- Database role with CONTROL on a user-defined role
CREATE ROLE [AddMemberTest_DbRole_CanControlDbRole];
CREATE ROLE [AddMemberTest_DbRole_TargetOf_DbRole_CanControlDbRole];
GRANT CONTROL ON ROLE::[AddMemberTest_DbRole_TargetOf_DbRole_CanControlDbRole] TO [AddMemberTest_DbRole_CanControlDbRole];
-- Database role with ALTER ANY ROLE can add to any user-defined role
CREATE ROLE [AddMemberTest_DbRole_CanAlterAnyDbRole];
GRANT ALTER ANY ROLE TO [AddMemberTest_DbRole_CanAlterAnyDbRole];
-- Database role with ALTER on database (grants ALTER ANY ROLE) can add to user-defined roles
CREATE ROLE [AddMemberTest_DbRole_CanAlterDb]
GRANT ALTER ON DATABASE::[EdgeTest_AddMember] TO [AddMemberTest_DbRole_CanAlterDb]
-- =====================================================
-- DATABASE LEVEL: ApplicationRole -> DatabaseRole
-- =====================================================
-- Application role with ALTER on user-defined role
CREATE APPLICATION ROLE [AddMemberTest_AppRole_CanAlterDbRole] WITH PASSWORD = 'AppRoleP@ss123!';
CREATE ROLE [AddMemberTest_DbRole_TargetOf_AppRole_CanAlterDbRole];
GRANT ALTER ON ROLE::[AddMemberTest_DbRole_TargetOf_AppRole_CanAlterDbRole] TO [AddMemberTest_AppRole_CanAlterDbRole];
-- Application role with CONTROL on user-defined role
CREATE APPLICATION ROLE [AddMemberTest_AppRole_CanControlDbRole] WITH PASSWORD = 'AppRoleP@ss123!';
CREATE ROLE [AddMemberTest_DbRole_TargetOf_AppRole_CanControlDbRole];
GRANT CONTROL ON ROLE::[AddMemberTest_DbRole_TargetOf_AppRole_CanControlDbRole] TO [AddMemberTest_AppRole_CanControlDbRole];
-- Application role with ALTER ANY ROLE can add to any user-defined role
CREATE APPLICATION ROLE [AddMemberTest_AppRole_CanAlterAnyDbRole] WITH PASSWORD = 'AppRoleP@ss123!';
GRANT ALTER ANY ROLE TO [AddMemberTest_AppRole_CanAlterAnyDbRole];
-- Application role with ALTER on database (grants ALTER ANY ROLE) can add to user-defined roles
CREATE APPLICATION ROLE [AddMemberTest_AppRole_CanAlterDb] WITH PASSWORD = 'EdgeTestP@ss123!';
GRANT ALTER ON DATABASE::[EdgeTest_AddMember] TO [AddMemberTest_AppRole_CanAlterDb];
USE master;
GO
PRINT 'MSSQL_AddMember test setup completed';
'@
# Define setup SQL for MSSQL_Alter
$script:SetupSQL_Alter = @'
USE master;
GO
-- =====================================================
-- COMPLETE SETUP FOR MSSQL_Alter EDGE TESTING
-- =====================================================
-- This creates all objects needed to test every source/target
-- combination for MSSQL_Alter edges (offensive, non-traversable)
-- Create test database if it doesn't exist
CREATE DATABASE [EdgeTest_Alter];
GO
-- =====================================================
-- SERVER LEVEL: Login/ServerRole -> ServerRole
-- =====================================================
-- Note: There is no ALTER permission on the server itself
-- Login with ALTER permission on login
CREATE LOGIN [AlterTest_Login_CanAlterLogin] WITH PASSWORD = 'EdgeTestP@ss123!';
CREATE LOGIN [AlterTest_Login_TargetOf_Login_CanAlterLogin] WITH PASSWORD = 'EdgeTestP@ss123!';
GRANT ALTER ON LOGIN::[AlterTest_Login_TargetOf_Login_CanAlterLogin] TO [AlterTest_Login_CanAlterLogin];
-- Login with ALTER permission on server role
CREATE LOGIN [AlterTest_Login_CanAlterServerRole] WITH PASSWORD = 'EdgeTestP@ss123!';
CREATE SERVER ROLE [AlterTest_ServerRole_TargetOf_Login_CanAlterServerRole];
GRANT ALTER ON SERVER ROLE::[AlterTest_ServerRole_TargetOf_Login_CanAlterServerRole] TO [AlterTest_Login_CanAlterServerRole];
-- ServerRole with ALTER permission on login
CREATE SERVER ROLE [AlterTest_ServerRole_CanAlterLogin];
CREATE LOGIN [AlterTest_Login_TargetOf_ServerRole_CanAlterLogin] WITH PASSWORD = 'EdgeTestP@ss123!';
GRANT ALTER ON LOGIN::[AlterTest_Login_TargetOf_ServerRole_CanAlterLogin] TO [AlterTest_ServerRole_CanAlterLogin];
-- ServerRole with ALTER permission on server role
CREATE SERVER ROLE [AlterTest_ServerRole_CanAlterServerRole];
CREATE SERVER ROLE [AlterTest_ServerRole_TargetOf_ServerRole_CanAlterServerRole];
GRANT ALTER ON SERVER ROLE::[AlterTest_ServerRole_TargetOf_ServerRole_CanAlterServerRole] TO [AlterTest_ServerRole_CanAlterServerRole];
-- =====================================================
-- DATABASE LEVEL SETUP
-- =====================================================
USE [EdgeTest_Alter];
GO
-- =====================================================
-- DATABASE LEVEL: DatabaseUser/DatabaseRole/ApplicationRole -> Database
-- =====================================================
-- DatabaseUser with ALTER on database
CREATE USER [AlterTest_User_CanAlterDb] WITHOUT LOGIN;
GRANT ALTER ON DATABASE::[EdgeTest_Alter] TO [AlterTest_User_CanAlterDb];
-- DatabaseRole with ALTER on database
CREATE ROLE [AlterTest_DbRole_CanAlterDb];
GRANT ALTER ON DATABASE::[EdgeTest_Alter] TO [AlterTest_DbRole_CanAlterDb];
-- ApplicationRole with ALTER on database
CREATE APPLICATION ROLE [AlterTest_AppRole_CanAlterDb] WITH PASSWORD = 'AppRoleP@ss123!';
GRANT ALTER ON DATABASE::[EdgeTest_Alter] TO [AlterTest_AppRole_CanAlterDb];
-- =====================================================
-- DATABASE LEVEL: DatabaseUser/DatabaseRole/ApplicationRole -> DatabaseUser
-- =====================================================
-- DatabaseUser with ALTER on database user
CREATE USER [AlterTest_User_CanAlterDbUser] WITHOUT LOGIN;
CREATE USER [AlterTest_User_TargetOf_User_CanAlterDbUser] WITHOUT LOGIN;
GRANT ALTER ON USER::[AlterTest_User_TargetOf_User_CanAlterDbUser] TO [AlterTest_User_CanAlterDbUser];
-- DatabaseRole with ALTER on database user
CREATE ROLE [AlterTest_DbRole_CanAlterDbUser];
CREATE USER [AlterTest_User_TargetOf_DbRole_CanAlterDbUser] WITHOUT LOGIN;
GRANT ALTER ON USER::[AlterTest_User_TargetOf_DbRole_CanAlterDbUser] TO [AlterTest_DbRole_CanAlterDbUser];
-- ApplicationRole with ALTER on database user
CREATE APPLICATION ROLE [AlterTest_AppRole_CanAlterDbUser] WITH PASSWORD = 'AppRoleP@ss123!';
CREATE USER [AlterTest_User_TargetOf_AppRole_CanAlterDbUser] WITHOUT LOGIN;
GRANT ALTER ON USER::[AlterTest_User_TargetOf_AppRole_CanAlterDbUser] TO [AlterTest_AppRole_CanAlterDbUser];
-- =====================================================
-- DATABASE LEVEL: DatabaseUser/DatabaseRole/ApplicationRole -> DatabaseRole
-- =====================================================
-- DatabaseUser with ALTER on database role
CREATE USER [AlterTest_User_CanAlterDbRole] WITHOUT LOGIN;
CREATE ROLE [AlterTest_DbRole_TargetOf_User_CanAlterDbRole];
GRANT ALTER ON ROLE::[AlterTest_DbRole_TargetOf_User_CanAlterDbRole] TO [AlterTest_User_CanAlterDbRole];
-- DatabaseRole with ALTER on database role
CREATE ROLE [AlterTest_DbRole_CanAlterDbRole];
CREATE ROLE [AlterTest_DbRole_TargetOf_DbRole_CanAlterDbRole];
GRANT ALTER ON ROLE::[AlterTest_DbRole_TargetOf_DbRole_CanAlterDbRole] TO [AlterTest_DbRole_CanAlterDbRole];
-- ApplicationRole with ALTER on database role
CREATE APPLICATION ROLE [AlterTest_AppRole_CanAlterDbRole] WITH PASSWORD = 'AppRoleP@ss123!';
CREATE ROLE [AlterTest_DbRole_TargetOf_AppRole_CanAlterDbRole];
GRANT ALTER ON ROLE::[AlterTest_DbRole_TargetOf_AppRole_CanAlterDbRole] TO [AlterTest_AppRole_CanAlterDbRole];
-- =====================================================
-- DATABASE LEVEL: DatabaseUser/DatabaseRole/ApplicationRole -> ApplicationRole
-- =====================================================
-- DatabaseUser with ALTER on application role
CREATE USER [AlterTest_User_CanAlterAppRole] WITHOUT LOGIN;
CREATE APPLICATION ROLE [AlterTest_AppRole_TargetOf_User_CanAlterAppRole] WITH PASSWORD = 'AppRoleP@ss123!';
GRANT ALTER ON APPLICATION ROLE::[AlterTest_AppRole_TargetOf_User_CanAlterAppRole] TO [AlterTest_User_CanAlterAppRole];
-- DatabaseRole with ALTER on application role
CREATE ROLE [AlterTest_DbRole_CanAlterAppRole];
CREATE APPLICATION ROLE [AlterTest_AppRole_TargetOf_DbRole_CanAlterAppRole] WITH PASSWORD = 'AppRoleP@ss123!';
GRANT ALTER ON APPLICATION ROLE::[AlterTest_AppRole_TargetOf_DbRole_CanAlterAppRole] TO [AlterTest_DbRole_CanAlterAppRole];
-- ApplicationRole with ALTER on application role
CREATE APPLICATION ROLE [AlterTest_AppRole_CanAlterAppRole] WITH PASSWORD = 'AppRoleP@ss123!';
CREATE APPLICATION ROLE [AlterTest_AppRole_TargetOf_AppRole_CanAlterAppRole] WITH PASSWORD = 'AppRoleP@ss123!';
GRANT ALTER ON APPLICATION ROLE::[AlterTest_AppRole_TargetOf_AppRole_CanAlterAppRole] TO [AlterTest_AppRole_CanAlterAppRole];
USE master;
GO
PRINT 'MSSQL_Alter test setup completed';
'@
# Define setup SQL for MSSQL_AlterAnyAppRole
$script:SetupSQL_AlterAnyAppRole = @'
USE master;
GO
-- =====================================================
-- COMPLETE SETUP FOR MSSQL_AlterAnyAppRole EDGE TESTING
-- =====================================================
-- This creates all objects needed to test every source/target
-- combination for MSSQL_AlterAnyAppRole edges