-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConfigManBearPig.ps1
More file actions
10441 lines (8990 loc) · 483 KB
/
ConfigManBearPig.ps1
File metadata and controls
10441 lines (8990 loc) · 483 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
ConfigManBearPig: PowerShell collector for adding SCCM attack paths to BloodHound with OpenGraph
.DESCRIPTION
Author: Chris Thompson (@_Mayyhem) at SpecterOps
Purpose:
Collects BloodHound OpenGraph compatible SCCM data following these ordered steps:
1. LDAP (identify sites, site servers, fallback status points, and management points in System Management container)
2. Local (identify management points and distribution points in logs when running this script on an SCCM client)
3. DNS (identify management points published to DNS)
4. *DHCP (identify PXE-enabled distribution points and management points in boot media)
5. Remote Registry (identify site servers, site databases, and current users on targets)
6. MSSQL (check database servers for Extended Protection for Authentication)
7. AdminService (collect information from SMS Providers with privileges to query site information)
8. *WMI (if AdminService collection fails)
9. HTTP (identify management points, distribution points, and SMS Providers via exposed web services)
10. SMB (identify site servers and distribution points via file shares)
System Requirements:
- PowerShell 4.0 or higher
- Active Directory domain context with line of sight to a domain controller
- Various permissions based on collection methods used
Limitations:
- You MUST include the 'MSSQL' collection method to remotely identify EPA settings on site database servers with any domain user (or 'RemoteRegistry' to collect from the registry with admin privileges on the system hosting the database).
- SCCM hierarchies don't have their own unique identifier, so the site code for the site that data is collected from is used in the identifier for objects (e.g., SMS00001@PS1), preventing merging of objects if there are more than one hierarchy in the same graph database (e.g., both hierarchies will have the SMS00001 collection but different members), but causing duplicate objects if collecting from two sites within the same hierarchy.
- If the same site code exists more than once in the environment (Microsoft recommends against this, so it shouldn't), the nodes and edges for those sites will be merged, causing false positives in the graph. This is not recommended within the same forest: https://learn.microsoft.com/en-us/intune/configmgr/core/servers/deploy/install/prepare-to-install-sites#bkmk_sitecodes
- It is assumed in some cases (e.g., during DP and SMS Provider collection) that a single system does not host site system roles in more than one site. If this is the case, only one site code will be associated with that system.
- CoerceAndRelayNTLMtoSMB collection doesn't work because post-processed AdminTo edges can't be added via OpenGraph yet, so added CoerceAndRelayToSMB edges instead
- MSSQL collection assumes that any collection target hosting a SQL Server instance is a site database server. If there are other SQL Servers in the environment, false positives may occur.
- I'm not a hooking expert, so if you see crashes during MSSQL collection due to the InitializeSecurityContextW hooking method that's totally vibe-coded, disable it. The hooking function doesn't work in PowerShell v7+ due to lack of support for certain APIs.
In Progress / To Do:
- Entity panels
- Get members of groups with permissions on System Management container
- Test with SQL on non-standard port
- Remove hardcoded port 1433 from AdminService collection
- Relay management point computer accounts to site databases
- Secondary site databases
- Group and user collection members
- Parse task sequences and collection variables for usernames and passwords during Local collection
- DHCP collection (unauthenticated network access)
- WMI collection (privileged, fallback if AdminService is not reachable)
- CMPivot collection (privileged)
.PARAMETER Help
Display usage information
.PARAMETER CollectionMethods
Collection methods to use (comma-separated):
- All (default): All SCCM collection methods
- LDAP
- Local
- DNS
- DHCP
- RemoteRegistry
- MSSQL
- AdminService
- WMI
- HTTP
- SMB
.PARAMETER ComputerFile
Specify the path to a file containing computer targets (limits to Remote Registry, MSSQL, AdminService, HTTP, SMB)
.PARAMETER Computers
Specify a comma-separated list of computer names or IP addresses to target (limits to Remote Registry, MSSQL, AdminService, WMI, HTTP, SMB)
.PARAMETER SMSProvider
Specify a specific SMS Provider to collect from (limits to AdminService, WMI)
.PARAMETER SiteCodes
Specify site codes to use for DNS collection (file path or comma-separated string):
- File: Path to file containing site codes (one per line)
- String: Comma-separated site codes (e.g., "PS1,CAS,PS2")
Increases success rate of querying of DNS for management point records for the specified sites (when LDAP/Local collection fail to identify a site code or to supplement discovered site codes)
.PARAMETER OutputFormat
Supported values:
- Zip (default): OpenGraph implementation, outputs .zip containing .json file
- CustomNodes: Outputs only custom nodes to .json file for BloodHound API
.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 TempDir
Specify the path to a temporary directory where .json files will be stored before being zipped
.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: 95)
.PARAMETER LogFile
Specify the path to a log file to write script log to
.PARAMETER Domain
Specify a domain to use for LDAP queries and name resolution
.PARAMETER DomainController
Specify a domain controller to use for DNS and AD object resolution
.PARAMETER DisablePossibleEdges
Switch/Flag:
- Off (default): Make the following edges traversable (useful for offensive engagements but extends duration and is prone to false positive edges that may not be abusable):
- CoerceAndRelayToMSSQL: EPA setting is assumed to be Off if the MSSQL server can't be reached
- MSSQL_*: Assume any targeted MSSQL Server instances are site database servers, which may create false positives if MSSQL is installed on SCCM-related targets for other purposes, otherwise use Remote Registry collection to confirm
- SameHostAs/SCCM_HasClient: Systems with the CmRcService SPN are treated as client devices in the root site for the forest (may be false positive if SCCM client was removed after remote control was used)
- SCCM_HasNetworkAccessAccount: the NAA password may not be valid
- On: The edges above are not created or are created as non-traversable to reduce false positives at the expense of possible edges
.PARAMETER EnableBadOpsec
Switch/Flag:
- Off (default): Do not create edges that launch cmd.exe/powershell.exe or access SYSTEM DPAPI keys on the system where ConfigManBearPig is executed (e.g., to dump and decrypt the NAA username)
- On: Create the edges above (WILL be detected by EDR/AV solutions)
.PARAMETER ShowCleartextPasswords
Switch/Flag:
- Off (default): Do not decrypt or display cleartext passwords
- On: Display cleartext passwords when they are discovered
.PARAMETER Verbose
Enable verbose output
#>
[CmdletBinding()]
param(
[switch]$Help,
[string]$CollectionMethods = "All",
[string]$ComputerFile,
[string]$Computers,
[string]$SMSProvider,
[string]$SiteCodes,
[string]$OutputFormat = "Zip",
[string]$FileSizeLimit = "1GB",
[string]$FileSizeUpdateInterval = "5",
[string]$TempDir,
[string]$ZipDir,
[int]$MemoryThresholdPercent = 95,
[string]$LogFile = "ConfigManBearPig_output.log",
[string]$Domain = $env:USERDNSDOMAIN,
[string]$DomainController,
[switch]$DisablePossibleEdges,
[switch]$EnableBadOpsec,
[switch]$ShowCleartextPasswords,
[switch]$Version
)
#region Logging
function Write-LogMessage {
param(
[string]$Level = "Info",
[string]$Message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"Error" { "Red" }
"Warning" { "Yellow" }
"Success" { "Green" }
"Info" { "White" }
"Verbose" { "DarkGray" }
"Debug" { "DarkYellow" }
default { "White" }
}
$padding = " " * (9 - $Level.Length)
$logEntry = "[$timestamp] [$Level]$padding $Message"
# File output
if ($LogFile) {
$logEntry | Out-File -FilePath $LogFile -Append -Encoding UTF8
}
# Only print Verbose when $VerbosePreference is set to Continue
if ($Level -eq "Verbose" -and $VerbosePreference -ne "Continue") {
return
}
Write-Host "[$timestamp] [$Level]$padding $Message" -ForegroundColor $color
}
#endregion
#region Error Handling and Validation
function Test-Prerequisites {
$issues = @()
# Check PowerShell version
if ($PSVersionTable.PSVersion.Major -lt 4) {
$issues += "PowerShell 4.0 or higher is required"
}
# Check if running in domain context
if (-not $script:Domain) {
$issues += "No domain context detected. Specify -Domain parameter or ensure machine is domain-joined"
}
# Check permissions
if ($CollectionMethods -contains 'Local' -or $CollectionMethods -contains 'All' -or $CollectionMethods -eq '') {
$isAdmin = Test-AdminPrivileges
if (-not $isAdmin) {
Write-LogMessage Warning "Not running as administrator. Local collection method may fail."
}
}
# Validate ComputerFile if specified
if ($ComputerFile -and -not (Test-Path $ComputerFile)) {
$issues += "ComputerFile not found: $ComputerFile"
}
# Validate output directories
if ($TempDir -and -not (Test-Path $TempDir)) {
try {
New-Item -ItemType Directory -Path $TempDir -Force | Out-Null
} catch {
$issues += "Cannot create TempDir: $TempDir"
}
}
if ($ZipDir -and -not (Test-Path $ZipDir)) {
try {
New-Item -ItemType Directory -Path $ZipDir -Force | Out-Null
} catch {
$issues += "Cannot create ZipDir: $ZipDir"
}
}
if ($issues.Count -gt 0) {
Write-LogMessage Error "Prerequisites check failed:"
foreach ($issue in $issues) {
Write-LogMessage Error " $issue"
}
return $false
}
Write-LogMessage Success "Prerequisites check passed"
return $true
}
#endregion
#region Phase Orchestration
# Phases that run ONCE for the whole run (can add targets)
#$script:PhasesOnce = @('LDAP','Local','DNS','DHCP')
$script:PhasesOnce = @('LDAP','Local','DNS')
# Phases that run PER HOST
#$script:PhasesPerHost = @('RemoteRegistry','MSSQL','AdminService','WMI','HTTP','SMB')
$script:PhasesPerHost = @('RemoteRegistry','MSSQL','AdminService','HTTP','SMB')
# Canonical overall order (for selection + display)
$script:AllPhases = $script:PhasesOnce + $script:PhasesPerHost
# Map of phase -> scriptblock
# - Once phases: { param() <do global work; may add to $script:CollectionTargets> }
# - Per-host phases: { param($Target) <work per device> }
$script:PhaseActionsOnce = @{
LDAP = { Invoke-LDAPCollection; }
DHCP = { Invoke-DHCPCollection; }
Local = { Invoke-LocalCollection; }
DNS = { Invoke-DNSCollection; }
}
$script:PhaseActionsPerHost = @{
RemoteRegistry = { param($Target) Write-LogMessage Verbose "RemoteRegistry -> $($Target.Hostname) starting"; Invoke-RemoteRegistryCollection -CollectionTarget $Target; }
MSSQL = { param($Target) Write-LogMessage Verbose "MSSQL -> $($Target.Hostname) starting"; Invoke-MSSQLCollection -CollectionTarget $Target; }
AdminService = { param($Target) Write-LogMessage Verbose "AdminService -> $($Target.Hostname) starting"; Invoke-AdminServiceCollection -CollectionTarget $Target; }
WMI = { param($Target) Write-LogMessage Verbose "WMI -> $($Target.Hostname) starting"; Invoke-WMICollection -Target $Target; }
HTTP = { param($Target) Write-LogMessage Verbose "HTTP -> $($Target.Hostname) starting"; Invoke-HTTPCollection -CollectionTarget $Target; }
SMB = { param($Target) Write-LogMessage Verbose "SMB -> $($Target.Hostname) starting"; Invoke-SMBCollection -CollectionTarget $Target; }
}
function Get-SelectedPhases {
param([string]$Methods)
$tokens = ($Methods -split ',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }
if (-not $tokens -or $tokens -contains 'ALL') { return $script:AllPhases }
$wanted = @{}
foreach ($t in $tokens) { $wanted[$t.ToUpper()] = $true }
$script:AllPhases | Where-Object { $wanted.ContainsKey($_.ToUpper()) }
}
# Global (once) phase status
# Values: Pending / Success / Failed
$script:GlobalPhaseStatus = @{}
function Ensure-GlobalPhaseStatus {
param([string[]]$SelectedPhases)
foreach ($p in ($SelectedPhases | Where-Object { $_ -in $script:PhasesOnce })) {
if (-not $script:GlobalPhaseStatus.ContainsKey($p)) {
$script:GlobalPhaseStatus[$p] = 'Pending'
}
}
}
# Per-host phase status (per device)
# device.PhaseStatus[phase] = Pending / Success / Failed
function Ensure-PerHostPhaseStatus {
param([string[]]$SelectedPhases)
$perHost = $SelectedPhases | Where-Object { $_ -in $script:PhasesPerHost }
foreach ($d in $script:CollectionTargets.Values) {
if (-not $d.PSObject.Properties.Match('PhaseStatus')) {
$d | Add-Member -NotePropertyName PhaseStatus -NotePropertyValue @{}
}
foreach ($p in $perHost) {
if (-not $d.PhaseStatus.ContainsKey($p)) { $d.PhaseStatus[$p] = 'Pending' }
}
}
}
function Invoke-DiscoveryPipeline {
param(
[string[]]$SelectedPhases
)
# 1) Run ONCE phases in order (only those selected)
Ensure-GlobalPhaseStatus -SelectedPhases $SelectedPhases
foreach ($phase in $script:PhasesOnce) {
if ($phase -notin $SelectedPhases) { continue }
if ($script:GlobalPhaseStatus[$phase] -ne 'Pending') { continue }
try {
& $script:PhaseActionsOnce[$phase] # no target; may add to $script:CollectionTargets
$script:GlobalPhaseStatus[$phase] = 'Success'
} catch {
$script:GlobalPhaseStatus[$phase] = 'Failed'
Write-LogMessage Error "$phase phase failed: $_"
}
}
# 2) Run PER-HOST phases until none remain Pending
while ($true) {
if ($script:stopProcessing) { break }
Ensure-PerHostPhaseStatus -SelectedPhases $SelectedPhases
$didWorkThisPass = $false
foreach ($phase in $script:PhasesPerHost) {
if ($phase -notin $SelectedPhases) { continue }
$pending = $script:CollectionTargets.Values |
Where-Object { $_.PhaseStatus[$phase] -eq 'Pending' }
if (-not $pending) { continue }
$didWorkThisPass = $true
# Always run per-host phases serially
foreach ($t in $pending) {
try {
& $script:PhaseActionsPerHost[$phase] -Target $t
$t.PhaseStatus[$phase] = 'Success'
# Periodic maintenance: run every 10 seconds during collection
if (-not $script:LastMaintenanceCheck) { $script:LastMaintenanceCheck = Get-Date }
if ((Get-Date) -ge $script:LastMaintenanceCheck.AddSeconds(10)) {
if (-not (Test-MemoryUsage -Threshold $MemoryThresholdPercent)) {
Write-LogMessage Error "Stopping enumeration due to high memory usage"
$script:stopProcessing = $true
break
}
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.GC]::Collect()
$script:LastMaintenanceCheck = Get-Date
}
if ($script:stopProcessing) { break }
} catch {
$t.PhaseStatus[$phase] = 'Failed'
Write-LogMessage Error "$phase phase failed on $($t.Hostname): $_"
}
}
if ($script:stopProcessing) { break }
}
if (-not $didWorkThisPass) { break } # no pending work left for any per-host phase
}
Write-LogMessage Success "All selected phases completed. Once phases ran once; per-host phases ran for every discovered target."
}
#endregion
#region DNS Resolution
function Test-DnsResolution {
param([string]$Domain)
if (-not $Domain) {
return $false
}
Write-LogMessage Verbose "Testing DNS resolution for $Domain"
try {
# Try to resolve the domain
if ($script:DomainController) {
Write-LogMessage Verbose "Using specified domain controller $script:DomainController for DNS resolution"
try {
if (Get-Command Resolve-DnsName -ErrorAction SilentlyContinue) {
$dnsResult = (Resolve-DnsName -Name $Domain -Server $script:DomainController -ErrorAction Stop).IPAddress
}
} catch {
Write-LogMessage Verbose "Failed to resolve $Domain using DC $script:DomainController: $_"
}
}
# Fallback to standard resolution
if (-not $dnsResult) {
$dnsResult = [System.Net.Dns]::GetHostAddresses($Domain)
}
if ($dnsResult -and $dnsResult.Count -gt 0) {
return $true
}
} catch {
Write-LogMessage Error "Failed to resolve domain '$Domain': $_"
return $false
}
}
function Resolve-PrincipalInDomain {
param (
[string]$Name,
[string]$Domain
)
# Initialize domain cache for discovered domain suffixes
if (-not $script:DiscoveredDomains) { $script:DiscoveredDomains = @{} }
# Initialize and check cache to avoid repeated lookups
if (-not $script:ResolvedPrincipalCache) { $script:ResolvedPrincipalCache = @{} }
# Handle DOMAIN\username format by normalizing to just the username portion
if ($Name -match '^([^\\]+)\\(.+)$') {
$usernamePart = $matches[2]
Write-LogMessage Verbose "Detected DOMAIN\username format for '$Name'; resolving username '$usernamePart'"
$Name = $usernamePart
}
# Short-circuit immediately if all domains have already been tried for this name
if ($script:ResolvedPrincipalCache.ContainsKey("ALL|$($Name.ToLower())")) {
Write-LogMessage Verbose "All domains already attempted for '$Name', returning cached failure"
return $null
}
# Extract domain suffix from FQDN if present
$domainsToTry = @()
if ($Name -match '\.') {
# Name appears to be an FQDN, extract potential domain suffix
$nameParts = $Name -split '\.'
if ($nameParts.Count -gt 2) {
# Try extracting domain from FQDN (everything after first part)
$extractedDomain = ($nameParts[1..($nameParts.Count - 1)] -join '.').ToUpper()
if ($extractedDomain -ne $Domain.ToUpper()) {
$domainsToTry += $extractedDomain
Write-LogMessage Verbose "Extracted domain suffix '$extractedDomain' from FQDN '$Name'"
# Add to discovered domains cache
if (-not $script:DiscoveredDomains.ContainsKey($extractedDomain)) {
$script:DiscoveredDomains[$extractedDomain] = $true
Write-LogMessage Verbose "Added '$extractedDomain' to discovered domains cache"
}
}
}
}
# Add the originally specified domain
if ($Domain) {
$domainsToTry += $Domain
}
# Try resolution in each domain
foreach ($domainToTry in $domainsToTry) {
$cacheKey = ("{0}|{1}" -f $domainToTry, $Name).ToLower()
# Check cache first
if ($script:ResolvedPrincipalCache.ContainsKey($cacheKey)) {
if ($script:ResolvedPrincipalCache[$cacheKey] -eq $null) {
Write-LogMessage Verbose "Already tried to resolve $Name in domain $domainToTry and failed, trying next domain"
continue
}
Write-LogMessage Verbose "Resolved $Name in domain $domainToTry from cache"
return $script:ResolvedPrincipalCache[$cacheKey]
}
Write-LogMessage Verbose "Attempting to resolve $Name in domain $domainToTry"
$adPowershellSucceeded = $false
# Try Active Directory PowerShell module first
if (Get-Command -Name Get-ADComputer -ErrorAction SilentlyContinue) {
Write-LogMessage Verbose "Trying AD PowerShell module in domain $domainToTry"
try {
$adObject = $null
# Set server parameter if domain is specified and different from current
$adParams = @{ Identity = $Name }
if ($script:DomainController) {
$adParams.Server = $script.DomainController
} elseif ($domainToTry -and $domainToTry -ne $env:USERDOMAIN -and $domainToTry -ne $env:USERDNSDOMAIN) {
$adParams.Server = $domainToTry
}
# Try Computer first
try {
$adObject = Get-ADComputer @adParams -ErrorAction Stop
} catch {
# Try Computer by SID
try {
$adParams.Remove('Identity')
$adParams.LDAPFilter = "(objectSid=$Name)"
$adObject = Get-ADComputer @adParams -ErrorAction Stop
if (-not $adObject) { throw }
} catch {
# Try User
try {
$adParams.Remove('LDAPFilter')
$adParams.Identity = $Name
$adObject = Get-ADUser @adParams -ErrorAction Stop
} catch {
# Try User by SID
try {
$adParams.Remove('Identity')
$adParams.LDAPFilter = "(objectSid=$Name)"
$adObject = Get-ADUser @adParams -ErrorAction Stop
if (-not $adObject) { throw }
} catch {
# Try Group
try {
$adParams.Remove('LDAPFilter')
$adParams.Identity = $Name
$adObject = Get-ADGroup @adParams -ErrorAction Stop
} catch {
# Try Group by SID
try {
$adParams.Remove('Identity')
$adParams.LDAPFilter = "(objectSid=$Name)"
$adObject = Get-ADGroup @adParams -ErrorAction Stop
if (-not $adObject) { throw }
} catch {
Write-LogMessage Verbose "No AD object found for '$Name' in domain '$domainToTry'"
}
}
}
}
}
}
if ($adObject) {
$adObjectName = if ($adObject.UserPrincipalName) { $adObject.UserPrincipalName } elseif ($adObject.DNSHostName) { $adObject.DNSHostName } else { $adObject.SamAccountName }
$adObjectSid = $adObject.SID.ToString()
Write-LogMessage Verbose "Resolved '$Name' to AD principal in '$domainToTry': $adObjectName ($adObjectSid)"
# Upper the first letter of object class to match BloodHound kind
$kind = if ($adObject.ObjectClass -and $adObject.ObjectClass.Length -gt 0) {
$adObject.ObjectClass.Substring(0,1).ToUpper() + $adObject.ObjectClass.Substring(1).ToLower()
} else {
$adObject.ObjectClass
}
$adPowershellSucceeded = $true
$result = [PSCustomObject]@{
name = $adObjectName
distinguishedName = $adObject.DistinguishedName
DNSHostName = $adObject.DNSHostName
Domain = $domainToTry
Enabled = $adObject.Enabled
IsDomainPrincipal = $true
SamAccountName = $adObject.SamAccountName
SID = $adObject.SID.ToString()
UserPrincipalName = $adObject.UserPrincipalName
Type = $kind
Error = $null
}
$script:ResolvedPrincipalCache[$cacheKey] = $result
return $result
}
} catch {
Write-LogMessage Verbose "AD PowerShell lookup failed for '$Name' in domain '$domainToTry': $_"
}
}
# Try ADSISearcher approach before .NET methods (.NET does not return dNSHostName property)
try {
Write-LogMessage Verbose "Attempting ADSISearcher for '$Name' in domain '$domainToTry'"
# Build LDAP path
$domainDN = if ($domainToTry) {
"DC=" + ($domainToTry -replace "\.", ",DC=")
} else {
$null
}
# Use Domain Controller in LDAP path if specified
$ldapPath = if ($script:DomainController -and $domainDN) {
"LDAP://$($script:DomainController)/$domainDN"
} elseif ($domainDN) {
"LDAP://$domainDN"
} else {
"LDAP://"
}
$adsiSearcher = if ($ldapPath -ne "LDAP://") {
New-Object System.DirectoryServices.DirectorySearcher([ADSI]$ldapPath)
} else {
New-Object System.DirectoryServices.DirectorySearcher
}
# Try different search filters
$searchFilters = @(
"(samAccountName=$Name)",
"(objectSid=$Name)",
"(userPrincipalName=$Name)",
"(dnsHostName=$Name)",
"(cn=$Name)"
)
$adsiResult = $null
foreach ($filter in $searchFilters) {
try {
$adsiSearcher.Filter = $filter
$adsiResult = $adsiSearcher.FindOne()
if ($adsiResult) {
Write-LogMessage Verbose "Found object using ADSISearcher with filter: $filter"
break
}
} catch {
Write-LogMessage Verbose "ADSISearcher filter '$filter' failed: $_"
}
}
if ($adsiResult) {
$props = $adsiResult.Properties
$objectClass = if ($props["objectclass"]) { $props["objectclass"][$props["objectclass"].Count - 1] } else { "unknown" }
$objectSid = $null
if ($props["objectsid"] -and $props["objectsid"][0]) {
try { $objectSid = [System.Security.Principal.SecurityIdentifier]::new([byte[]]$props["objectsid"][0], 0).Value } catch {}
}
$result = [PSCustomObject]@{
name = if ($props["userprincipalname"]) { $props["userprincipalname"][0] } elseif ($props["dnshostname"]) { $props["dnshostname"][0] } else { $props["samaccountname"][0] }
distinguishedName = if ($props["distinguishedname"]) { $props["distinguishedname"][0] } else { $null }
DNSHostName = if ($props["dnshostname"]) { $props["dnshostname"][0] } else { $null }
Domain = $domainToTry
Enabled = if ($props["useraccountcontrol"]) {
-not ([int]$props["useraccountcontrol"][0] -band 2)
} else {
$null
}
IsDomainPrincipal = $true
SamAccountName = if ($props["samaccountname"]) { $props["samaccountname"][0] } else { $null }
SID = $objectSid
UserPrincipalName = if ($props["userprincipalname"]) { $props["userprincipalname"][0] } else { $null }
Type = if ($objectClass -and $objectClass.Length -gt 0) {
$objectClass.Substring(0,1).ToUpper() + $objectClass.Substring(1).ToLower()
} else {
"Unknown"
}
Error = $null
}
$adsiSearcher.Dispose()
$script:ResolvedPrincipalCache[$cacheKey] = $result
return $result
}
$adsiSearcher.Dispose()
} catch {
Write-LogMessage Verbose "ADSISearcher lookup failed for '$Name' in domain '$domainToTry': $_"
}
# Try .NET DirectoryServices AccountManagement
if ($script:UseNetFallback -or -not (Get-Command -Name Get-ADComputer -ErrorAction SilentlyContinue) -or -not $adPowershellSucceeded) {
Write-LogMessage Verbose "Attempting .NET DirectoryServices AccountManagement for '$Name' in domain '$domainToTry'"
try {
# Try AccountManagement approach
# Use Domain Controller if specified
if ($script:DomainController) {
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext(
[System.DirectoryServices.AccountManagement.ContextType]::Domain,
$script:DomainController
)
} else {
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext(
[System.DirectoryServices.AccountManagement.ContextType]::Domain,
$domainToTry
)
}
$principal = $null
# Try as Computer
try {
$principal = [System.DirectoryServices.AccountManagement.ComputerPrincipal]::FindByIdentity($context, $Name)
if ($principal) {
Write-LogMessage Verbose "Found computer principal using .NET DirectoryServices: $($principal.Name)"
}
} catch {
Write-LogMessage Verbose "Computer lookup failed: $_"
}
# Try as User if computer lookup failed
if (-not $principal) {
try {
$principal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, $Name)
if ($principal) {
Write-LogMessage Verbose "Found user principal using .NET DirectoryServices: $($principal.Name)"
}
} catch {
Write-LogMessage Verbose "User lookup failed: $_"
}
}
# Try as Group if user lookup failed
if (-not $principal) {
try {
$principal = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, $Name)
if ($principal) {
Write-LogMessage Verbose "Found group principal using .NET DirectoryServices: $($principal.Name)"
}
} catch {
Write-LogMessage Verbose "Group lookup failed: $_"
}
}
if ($principal) {
$principalType = $principal.GetType().Name -replace "Principal$", ""
$result = [PSCustomObject]@{
name = if ($principal.UserPrincipalName) { $principal.UserPrincipalName } else { $principal.SamAccountName }
distinguishedName = $principal.DistinguishedName
DNSHostName = $principal.dNSHostName
Domain = $domainToTry
Enabled = if ($principal.PSObject.Properties['Enabled']) { $principal.Enabled } else { $null }
IsDomainPrincipal = $true
SamAccountName = $principal.SamAccountName
SID = $principal.Sid.Value
UserPrincipalName = $principal.UserPrincipalName
Type = $principalType
Error = $null
}
$context.Dispose()
$script:ResolvedPrincipalCache[$cacheKey] = $result
return $result
} else {
Write-LogMessage Verbose ".NET DirectoryServices failed to resolve '$Name' in domain '$domainToTry'"
}
$context.Dispose()
} catch {
Write-LogMessage Verbose ".NET DirectoryServices failed to resolve '$Name' in domain '$domainToTry': $_"
}
# Try DirectorySearcher as final .NET attempt
try {
Write-LogMessage Verbose "Attempting DirectorySearcher for '$Name' in domain '$domainToTry'"
Add-Type -AssemblyName System.DirectoryServices -ErrorAction Stop
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.Filter = "(|(samAccountName=$Name)(objectSid=$Name)(userPrincipalName=$Name)(dnsHostName=$Name))"
$null = $searcher.PropertiesToLoad.Add("samAccountName")
$null = $searcher.PropertiesToLoad.Add("objectSid")
$null = $searcher.PropertiesToLoad.Add("distinguishedName")
$null = $searcher.PropertiesToLoad.Add("userPrincipalName")
$null = $searcher.PropertiesToLoad.Add("dnsHostName")
$null = $searcher.PropertiesToLoad.Add("objectClass")
$null = $searcher.PropertiesToLoad.Add("userAccountControl")
$result = $searcher.FindOne()
if ($result) {
$objectClass = $result.Properties["objectclass"][$result.Properties["objectclass"].Count - 1]
$objectSid = $null
if ($result.Properties["objectsid"].Count -gt 0 -and $result.Properties["objectsid"][0]) {
try { $objectSid = [System.Security.Principal.SecurityIdentifier]::new([byte[]]$result.Properties["objectsid"][0], 0).Value } catch {}
}
Write-LogMessage Verbose "Found object using DirectorySearcher: $($result.Properties["samaccountname"][0])"
$returnResult = [PSCustomObject]@{
name = if ($result.Properties["userprincipalname"].Count -gt 0) { $result.Properties["userprincipalname"][0] } elseif ($result.Properties["dnshostname"].Count -gt 0) { $result.Properties["dnshostname"][0] } else { $result.Properties["samaccountname"][0] }
distinguishedName = $result.Properties["distinguishedname"][0]
DNSHostName = if ($result.Properties["dnshostname"].Count -gt 0) { $result.Properties["dnshostname"][0] } else { $null }
Domain = $domainToTry
Enabled = if ($result.Properties["useraccountcontrol"].Count -gt 0) {
-not ([int]$result.Properties["useraccountcontrol"][0] -band 2)
} else {
$null
}
IsDomainPrincipal = $true
SamAccountName = $result.Properties["samaccountname"][0]
SID = $objectSid
UserPrincipalName = if ($result.Properties["userprincipalname"].Count -gt 0) { $result.Properties["userprincipalname"][0] } else { $null }
Type = $objectClass.Substring(0,1).ToUpper() + $objectClass.Substring(1).ToLower()
Error = $null
}
$searcher.Dispose()
$script:ResolvedPrincipalCache[$cacheKey] = $returnResult
return $returnResult
}
$searcher.Dispose()
} catch {
Write-LogMessage Verbose "DirectorySearcher failed for '$Name' in domain '$domainToTry': $_"
}
}
# Try NTAccount translation
try {
Write-LogMessage Verbose "Attempting NTAccount translation for '$Name' in domain '$domainToTry'"
# Try direct SID lookup
$ntAccount = New-Object System.Security.Principal.NTAccount($domainToTry, $Name)
$sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier])
$resolvedSid = $sid.Value
Write-LogMessage Verbose "Resolved SID for '$Name' using NTAccount in '$domainToTry': $resolvedSid"
$ntResult = [PSCustomObject]@{
name = "$domainToTry\$Name"
SID = $resolvedSid
Domain = $domainToTry
Error = $null
}
$script:ResolvedPrincipalCache[$cacheKey] = $ntResult
return $ntResult
} catch {
Write-LogMessage Verbose "NTAccount translation failed for '$Name' in domain '$domainToTry': $_"
}
# Try SID to name translation as final attempt (if input looks like a SID)
if ($Name -match "^S-\d+-\d+") {
try {
Write-LogMessage Verbose "Attempting SID to name translation for '$Name'"
$sid = New-Object System.Security.Principal.SecurityIdentifier($Name)
$resolvedName = $sid.Translate([System.Security.Principal.NTAccount]).Value
Write-LogMessage Verbose "Resolved name for SID '$Name': $resolvedName"
$sidResult = [PSCustomObject]@{
name = $resolvedName
SID = $Name
Domain = $domainToTry
Error = $null
}
$script:ResolvedPrincipalCache[$cacheKey] = $sidResult
return $sidResult
} catch {
Write-LogMessage Verbose "SID to name translation failed for '$Name': $_"
}
}
# Mark this domain as failed in cache and continue to next domain
Write-LogMessage Verbose "Failed to resolve '$Name' in domain '$domainToTry', trying next domain if available"
$script:ResolvedPrincipalCache[$cacheKey] = $null
}
# All domains failed — cache globally so subsequent calls skip all domain lookups
$script:ResolvedPrincipalCache["ALL|$($Name.ToLower())"] = $null
Write-LogMessage Verbose "Failed to resolve '$Name' in all attempted domains"
return $null
}
function Get-ActiveDirectoryObject {
param (
[string]$Name = $null,
[string]$Sid = $null,
[string]$Domain = $script:Domain,
[string[]]$Properties = @("objectSid", "DNSHostName", "distinguishedName", "samAccountName", "userPrincipalName", "objectClass")
)
if ([string]::IsNullOrWhiteSpace($Name) -and [string]::IsNullOrWhiteSpace($Sid)) {
return $null
}
$searchValue = if ($Sid) { $Sid } else { $Name }
$isSearchBySid = -not [string]::IsNullOrWhiteSpace($Sid)
# Cache check — avoid re-querying AD for objects that already failed to resolve
if (-not $script:ADObjectCache) { $script:ADObjectCache = @{} }
$adObjCacheKey = "$($searchValue.ToLower())|$($Domain.ToLower())"
if ($script:ADObjectCache.ContainsKey($adObjCacheKey)) {
if ($script:ADObjectCache[$adObjCacheKey]) {
Write-LogMessage Verbose "Returning cached AD object for '$searchValue' in '$Domain'"
} else {
Write-LogMessage Verbose "Already failed to resolve '$searchValue' in '$Domain', skipping"
}
return $script:ADObjectCache[$adObjCacheKey]
}
if ($script:ADModuleAvailable) {
try {
$serverParam = @{}
if ($Domain -and $Domain -ne $env:USERDOMAIN -and $Domain -ne $env:USERDNSDOMAIN) {
$serverParam.Server = $Domain
}
if ($isSearchBySid) {
# Search by SID
try {
$adObject = Get-ADObject -Filter "objectSid -eq '$Sid'" @serverParam -Properties $Properties -ErrorAction Stop
if ($adObject) {
# Determine object type from objectClass
$objectType = switch -Regex ($adObject.objectClass[-1]) {
"computer" { "Computer" }
"user" { "User" }
"group" { "Group" }
default { $adObject.objectClass[-1] }
}
$script:ADObjectCache[$adObjCacheKey] = [PSCustomObject]@{
name = if ($adObject.DNSHostName) { $adObject.DNSHostName } elseif ($adObject.samAccountName) { "$Domain\$($adObject.samAccountName)" } else { "$Domain\$($adObject.Name)" }
SID = $adObject.objectSid.Value
domain = $Domain
type = $objectType
DNSHostName = $adObject.DNSHostName
distinguishedName = $adObject.DistinguishedName
samAccountName = $adObject.samAccountName
userPrincipalName = $adObject.userPrincipalName
objectClass = $adObject.objectClass
enabled = if ($adObject.PSObject.Properties.Name -contains "Enabled") { $adObject.Enabled } else { $null }
isDomainPrincipal = $true
}
return $script:ADObjectCache[$adObjCacheKey]
}
} catch {
Write-LogMessage Verbose "Failed to resolve SID '$Sid' using Get-ADObject: $_"
}
} else {
# Search by Name - try different search filters in priority order
$searchFilters = @(
"DNSHostName -eq '$Name'", # FQDN match
"samAccountName -eq '$Name'", # SAM account name
"userPrincipalName -eq '$Name'", # UPN for users
"Name -eq '$Name'" # Display name
)
# If name doesn't contain dot and doesn't end with $, try computer account format
if ($Name -notcontains '.' -and $Name -notlike '*$') {
$searchFilters += "samAccountName -eq '$Name$'"
}
foreach ($filter in $searchFilters) {
try {
$adObject = Get-ADObject -Filter $filter @serverParam -Properties $Properties -ErrorAction Stop
if ($adObject) {
# Determine object type from objectClass
$objectType = switch -Regex ($adObject.objectClass[-1]) {
"computer" { "Computer" }
"user" { "User" }
"group" { "Group" }
default { $adObject.objectClass[-1] }
}
$script:ADObjectCache[$adObjCacheKey] = [PSCustomObject]@{
name = if ($adObject.DNSHostName) { $adObject.DNSHostName } elseif ($adObject.samAccountName) { "$Domain\$($adObject.samAccountName)" } else { "$Domain\$($adObject.Name)" }
SID = if ($adObject.objectSid) { $adObject.objectSid.Value } else { $null }