-
Notifications
You must be signed in to change notification settings - Fork 2
/
PowerScan.ps1
executable file
·848 lines (730 loc) · 32.6 KB
/
PowerScan.ps1
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
Function Invoke-PowerScan {
<#
.SYNOPSIS
Query multiple computers via PowerShell script block.
Author: Timothée MENOCHET (@_tmenochet)
.DESCRIPTION
Invoke-PowerScan runs PowerShell script block targeting network ranges or Active Directory domain computers instead of a single host.
Multi-threading part is mostly stolen from PowerView by @harmj0y and @mattifestation.
.PARAMETER ScriptBlock
Specifies the PowerShell script block to run.
.PARAMETER ScriptParameters
Specifies the PowerShell script block arguments.
.PARAMETER ComputerArgument
Specifies the PowerShell script block argument name for target host, defaults to "ComputerName".
.PARAMETER ComputerList
Specifies the target hosts, such as specific addresses or network ranges (CIDR).
.PARAMETER ComputerDomain
Specifies an Active Directory domain for enumerating target computers.
.PARAMETER ComputerFilter
Specifies a specific role for enumerating target controllers, defaults to 'All'.
.PARAMETER SSL
Use SSL connection to LDAP server.
.PARAMETER Credential
Specifies the account to use for LDAP bind.
.PARAMETER LAPS
Adds LAPS credentials to script block parameters (experimental).
.PARAMETER Threads
Specifies the number of threads to use, defaults to 1.
.PARAMETER Quiet
Disables console output.
.PARAMETER NoCsv
Disables CSV output.
.PARAMETER OutputFile
Specifies CSV output file path, defaults to '.\$CurrentDate_$ModuleName.csv'
.EXAMPLE
PS C:\> Invoke-PowerScan -ScriptBlock ${Function:Get-OxidBinding} -ComputerList 192.168.1.0/24 -Quiet
.EXAMPLE
PS C:\> $cred = Get-Credential user@ADATUM.CORP
PS C:\> Invoke-PowerScan -ScriptBlock ${Function:Get-NetSession} -ScriptParameters @{Credential=$cred; Identity='john.doe'} -ComputerDomain ADATUM.CORP -Credential $cred
.EXAMPLE
PS C:\> Invoke-PowerScan -ScriptBlock ${Function:Get-LogonEvent} -ScriptParameters @{Identity='john.doe'} -ComputerFilter DomainControllers -NoCsv
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Management.Automation.ScriptBlock]
$ScriptBlock,
[ValidateNotNullOrEmpty()]
[Hashtable]
$ScriptParameters = @{},
[ValidateNotNullOrEmpty()]
[string]
$ComputerArgument = 'ComputerName',
[ValidateNotNullOrEmpty()]
[string[]]
$ComputerList,
[ValidateNotNullOrEmpty()]
[string]
$ComputerDomain = $Env:LOGONSERVER,
[ValidateSet('All', 'DomainControllers', 'Servers', 'Workstations')]
[String]
$ComputerFilter = 'All',
[Switch]
$SSL,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$Credential = [Management.Automation.PSCredential]::Empty,
[Switch]
$LAPS,
[ValidateNotNullOrEmpty()]
[Int]
$Threads = 1,
[Switch]
$Quiet,
[Switch]
$NoCsv,
[ValidateNotNullOrEmpty()]
[string]
$OutputFile = "$PWD\$(Get-Date -Format "yyyyMMdd-HH.mm.ss")_$($ScriptBlock.Ast.Name).csv"
)
$hostList = New-Object Collections.ArrayList
foreach ($computer in $ComputerList) {
if ($computer.Contains('/')) {
$hostList.AddRange($(New-IPv4RangeFromCIDR -CIDR $computer))
}
else {
$hostList.Add($computer) | Out-Null
}
}
if ($PSBoundParameters['ComputerDomain'] -or $PSBoundParameters['ComputerFilter']) {
switch ($ComputerFilter) {
'All' {
$filter = '(&(objectCategory=computer)(!userAccountControl:1.2.840.113556.1.4.803:=2))'
}
'DomainControllers' {
$filter = '(userAccountControl:1.2.840.113556.1.4.803:=8192)'
}
'Servers' {
$filter = '(&(objectCategory=computer)(operatingSystem=*server*)(!userAccountControl:1.2.840.113556.1.4.803:=2)(!userAccountControl:1.2.840.113556.1.4.803:=8192))'
}
'Workstations' {
$filter = '(&(objectCategory=computer)(!operatingSystem=*server*)(!userAccountControl:1.2.840.113556.1.4.803:=2))'
}
}
Get-LdapObject -Server $ComputerDomain -SSL:$SSL -Filter $filter -Properties 'dnshostname' -Credential $Credential | ForEach-Object {
if ($computer = $_.dnshostname) {
$hostList.Add($computer.ToString()) | Out-Null
}
}
}
if ($LAPS) {
# Pass credential to ScriptBlock for Get-LapsCredential call
$ScriptParameters.Add('Credential', $Credential)
# Get-LapsCredential call definition
$lapsBlock = [Environment]::NewLine
$lapsBlock += 'if ($lapsCreds = Get-LapsCredential -Server "' + $ComputerDomain + '" -SSL:$' + $SSL + ' -Credential $Credential -ComputerName $' + $ComputerArgument + ') {$Credential = $lapsCreds}'
$lapsBlock += [Environment]::NewLine
# Modify script block
$count = 0
try {
$finalBlock = $ScriptBlock.Ast.Body.Extent.Text.Substring(1, $ScriptBlock.Ast.Body.ParamBlock.Extent.StartOffset - $ScriptBlock.Ast.Body.Extent.StartOffset - 1)
}
catch {
$finalBlock = ''
}
if ($ScriptBlock.Ast.Body.ParamBlock) {
# Add PARAM block
$finalBlock += $ScriptBlock.Ast.Body.ParamBlock.ToString()
$finalBlock += [Environment]::NewLine
}
if ($ScriptBlock.Ast.Body.BeginBlock) {
# Modify BEGIN block
$finalBlock += 'BEGIN {'
$finalBlock += $lapsBlock
foreach ($block in $ScriptBlock.Ast.Body.BeginBlock.Statements) {
$finalBlock += $block.ToString()
$finalBlock += [Environment]::NewLine
}
$finalBlock += '}'
$finalBlock += [Environment]::NewLine
$count++
}
if ($ScriptBlock.Ast.Body.ProcessBlock) {
if ($count) {
# Add PROCESS block
$finalBlock += $ScriptBlock.Ast.Body.ProcessBlock.ToString()
}
else {
# Modify PROCESS block
$finalBlock += 'PROCESS {'
$finalBlock += $lapsBlock
foreach ($block in $ScriptBlock.Ast.Body.ProcessBlock.Statements) {
$finalBlock += $block.ToString()
$finalBlock += [Environment]::NewLine
}
$finalBlock += '}'
}
$finalBlock += [Environment]::NewLine
$count++
}
if ($ScriptBlock.Ast.Body.EndBlock) {
if ($count) {
# Add END block
$finalBlock += $ScriptBlock.Ast.Body.EndBlock.ToString()
}
else {
# Case where BEGIN/PROCESS/END blocks are not specified
$finalBlock += $lapsBlock
$finalBlock += $ScriptBlock.ToString().Substring($ScriptBlock.Ast.Body.ParamBlock.Extent.StartOffset - $ScriptBlock.Ast.Body.Extent.StartOffset + $ScriptBlock.Ast.Body.ParamBlock.Extent.Text.Length)
}
$finalBlock += [Environment]::NewLine
$count++
}
$ScriptBlock = [scriptblock]::Create($finalBlock)
}
if ($Threads -eq 1 -or $hostList.Count -eq 1) {
foreach ($computer in $hostList) {
$params = $ScriptParameters.Clone()
$params.Add($ComputerArgument, $computer)
& $ScriptBlock @params *>&1 | Where-Object {$_} | ForEach-Object {
if (-not $Quiet) {
Write-Output $_
}
if (-not $NoCsv) {
$outputType = $_.GetType().Name
$_ | Where-Object {($outputType -ne 'VerboseRecord') -and ($outputType -ne 'WarningRecord') -and ($outputType -ne 'ErrorRecord')} `
| Out-CsvFile -Path $OutputFile -Append
}
}
}
}
else {
New-ThreadedFunction -ScriptBlock $ScriptBlock -ScriptParameters $ScriptParameters -Collection $hostList -CollectionParameter $ComputerArgument -Threads $Threads | Where-Object {$_} | ForEach-Object {
if (-not $Quiet) {
Write-Output $_
}
if (-not $NoCsv) {
$outputType = $_.GetType().Name
$_ | Where-Object {($outputType -ne 'VerboseRecord') -and ($outputType -ne 'WarningRecord') -and ($outputType -ne 'ErrorRecord')} `
| Out-CsvFile -Path $OutputFile -Append
}
}
}
}
# Adapted from Find-Fruit by @rvrsh3ll
Function Local:New-IPv4RangeFromCIDR {
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$CIDR
)
$hostList = New-Object Collections.ArrayList
$netPart = $CIDR.split("/")[0]
[uint32]$maskPart = $CIDR.split("/")[1]
$address = [Net.IPAddress]::Parse($netPart)
if ($maskPart -ge $address.GetAddressBytes().Length * 8) {
throw "Bad host mask"
}
$numhosts = [math]::Pow(2, (($address.GetAddressBytes().Length * 8) - $maskPart))
$startaddress = $address.GetAddressBytes()
[array]::Reverse($startaddress)
$startaddress = [BitConverter]::ToUInt32($startaddress, 0)
[uint32]$startMask = ([math]::Pow(2, $maskPart) - 1) * ([Math]::Pow(2, (32 - $maskPart)))
$startAddress = $startAddress -band $startMask
# In powershell 2.0 there are 4 0 bytes padded, so the [0..3] is necessary
$startAddress = [BitConverter]::GetBytes($startaddress)[0..3]
[array]::Reverse($startaddress)
$address = [Net.IPAddress][byte[]]$startAddress
for ($i = 0; $i -lt $numhosts - 2; $i++) {
$nextAddress = $address.GetAddressBytes()
[array]::Reverse($nextAddress)
$nextAddress = [BitConverter]::ToUInt32($nextAddress, 0)
$nextAddress++
$nextAddress = [BitConverter]::GetBytes($nextAddress)[0..3]
[array]::Reverse($nextAddress)
$address = [Net.IPAddress][byte[]]$nextAddress
$hostList.Add($address.IPAddressToString) | Out-Null
}
return $hostList
}
# Adapted from PowerView by @harmj0y and @mattifestation
Function Local:New-ThreadedFunction {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True)]
[String[]]
$Collection,
[ValidateNotNullOrEmpty()]
[String]
$CollectionParameter = 'ComputerName',
[Parameter(Mandatory = $True)]
[Management.Automation.ScriptBlock]
$ScriptBlock,
[Hashtable]
$ScriptParameters,
[Int]
[ValidateRange(1, 100)]
$Threads = 10,
[Switch]
$NoImports
)
BEGIN {
$SessionState = [Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
# Force a single-threaded apartment state (for token-impersonation stuffz)
$SessionState.ApartmentState = [Threading.ApartmentState]::STA
# Import the current session state's variables and functions so the chained functionality can be used by the threaded blocks
if (-not $NoImports) {
# Grab all the current variables for this runspace
$MyVars = Get-Variable -Scope 2
# These variables are added by Runspace.Open() method and produce Stop errors if added twice
$VorbiddenVars = @('?','args','ConsoleFileName','Error','ExecutionContext','false','HOME','Host','input','InputObject','MaximumAliasCount','MaximumDriveCount','MaximumErrorCount','MaximumFunctionCount','MaximumHistoryCount','MaximumVariableCount','MyInvocation','null','PID','PSBoundParameters','PSCommandPath','PSCulture','PSDefaultParameterValues','PSHOME','PSScriptRoot','PSUICulture','PSVersionTable','PWD','ShellId','SynchronizedHash','true')
# Add variables from Parent Scope (current runspace) into the InitialSessionState
foreach ($Var in $MyVars) {
if ($VorbiddenVars -NotContains $Var.Name) {
$SessionState.Variables.Add((New-Object -TypeName Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList $Var.name,$Var.Value,$Var.description,$Var.options,$Var.attributes))
}
}
# Add functions from current runspace to the InitialSessionState
foreach ($Function in (Get-ChildItem Function:)) {
$SessionState.Commands.Add((New-Object -TypeName Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $Function.Name, $Function.Definition))
}
}
# Create a pool of $Threads runspaces
$Pool = [RunspaceFactory]::CreateRunspacePool(1, $Threads, $SessionState, $Host)
$Pool.Open()
# Get the proper BeginInvoke() method that allows for an output queue
$Method = $null
foreach ($M in [PowerShell].GetMethods() | Where-Object { $_.Name -eq 'BeginInvoke' }) {
$MethodParameters = $M.GetParameters()
if (($MethodParameters.Count -eq 2) -and $MethodParameters[0].Name -eq 'input' -and $MethodParameters[1].Name -eq 'output') {
$Method = $M.MakeGenericMethod([Object], [Object])
break
}
}
$Jobs = @()
$Collection = $Collection | Where-Object {$_ -and $_.Trim()}
if ($Threads -ge $Collection.Length) {
$Threads = $Collection.Length
}
Write-Verbose "[THREAD] Processing $($Collection.Count) elements with $Threads threads."
foreach ($Element in $Collection) {
# Create a "powershell pipeline runner"
$PowerShell = [PowerShell]::Create()
$PowerShell.runspacepool = $Pool
# Add the script block and arguments
$null = $PowerShell.AddScript($ScriptBlock).AddParameter($CollectionParameter, $Element)
if ($ScriptParameters) {
foreach ($Param in $ScriptParameters.GetEnumerator()) {
$null = $PowerShell.AddParameter($Param.Name, $Param.Value)
}
}
# Create the output queue
$Output = New-Object Management.Automation.PSDataCollection[Object]
# Start job
$Jobs += @{
PS = $PowerShell
Output = $Output
Result = $Method.Invoke($PowerShell, @($null, [Management.Automation.PSDataCollection[Object]]$Output))
Element = $Element
}
}
}
END {
Write-Verbose "[THREAD] Executing threads"
# Add element in each job output
foreach ($Job in $Jobs) {
$Job.Output | Add-Member -Force -MemberType NoteProperty -Name $CollectionParameter -Value $Job.Element
}
# Continuously loop through each job queue, consuming output as appropriate
do {
foreach ($Job in $Jobs) {
$Job.Output.ReadAll()
}
Start-Sleep -Seconds 1
}
while (($Jobs | Where-Object {-not $_.Result.IsCompleted}).Count -gt 0)
$SleepSeconds = 100
Write-Verbose "[THREAD] Waiting $SleepSeconds seconds for final cleanup..."
# Cleanup
for ($i=0; $i -lt $SleepSeconds; $i++) {
foreach ($Job in $Jobs) {
$Job.Output.ReadAll()
$Job.PS.Dispose()
}
Start-Sleep -Seconds 1
}
$Pool.Dispose()
Write-Verbose "[THREAD] All threads completed"
}
}
Function Local:Out-CsvFile {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Management.Automation.PSObject[]]
$InputObject,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Path,
[ValidateNotNullOrEmpty()]
[Char]
$Delimiter = ';',
[Switch]
$Append
)
BEGIN {
$outputPath = [IO.Path]::GetFullPath($Path)
$exists = [IO.File]::Exists($outputPath)
# Mutex so threaded code doesn't stomp on the output file
$mutex = New-Object Threading.Mutex $False,'CSVMutex'
$null = $mutex.WaitOne()
if ($Append) {
$fileMode = [IO.FileMode]::Append
}
else {
$fileMode = [IO.FileMode]::Create
$exists = $False
}
$csvStream = New-Object IO.FileStream($outputPath, $fileMode, [IO.FileAccess]::Write, [IO.FileShare]::Read)
$csvWriter = New-Object IO.StreamWriter($csvStream)
$csvWriter.AutoFlush = $True
}
PROCESS {
foreach ($entry in $InputObject) {
# Expand any collection properties
$entry = $entry | % {
$_.PSObject.Properties | % { $hash = @{} } { $hash.add($_.name, $_.value -join ", ") } { New-Object -TypeName psobject -Property $hash }
}
$objectCSV = ConvertTo-Csv -InputObject $entry -Delimiter $Delimiter -NoTypeInformation
if (-not $exists) {
# Output the object field names as well
$objectCSV | ForEach-Object { $csvWriter.WriteLine($_) }
$exists = $True
}
else {
# Only output object field data
$objectCSV[1..($objectCSV.Length-1)] | ForEach-Object { $csvWriter.WriteLine($_) }
}
}
}
END {
$mutex.ReleaseMutex()
$csvWriter.Dispose()
$csvStream.Dispose()
}
}
Function Local:Get-LdapRootDSE {
Param (
[ValidateNotNullOrEmpty()]
[String]
$Server = $Env:USERDNSDOMAIN,
[Switch]
$SSL
)
$searchString = "LDAP://$Server/RootDSE"
if ($SSL) {
# Note that the server certificate has to be trusted
$authType = [DirectoryServices.AuthenticationTypes]::SecureSocketsLayer
}
else {
$authType = [DirectoryServices.AuthenticationTypes]::Anonymous
}
$rootDSE = New-Object DirectoryServices.DirectoryEntry($searchString, $null, $null, $authType)
return $rootDSE
}
Function Local:Get-LdapObject {
Param (
[ValidateNotNullOrEmpty()]
[String]
$Server = $Env:USERDNSDOMAIN,
[Switch]
$SSL,
[ValidateNotNullOrEmpty()]
[String]
$SearchBase,
[ValidateSet('Base', 'OneLevel', 'Subtree')]
[String]
$SearchScope = 'Subtree',
[ValidateNotNullOrEmpty()]
[String]
$Filter = '(objectClass=*)',
[ValidateNotNullOrEmpty()]
[String[]]
$Properties = '*',
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$Credential = [Management.Automation.PSCredential]::Empty
)
Begin {
if ((-not $SearchBase) -or $SSL) {
# Get default naming context
try {
$rootDSE = Get-LdapRootDSE -Server $Server
$defaultNC = $rootDSE.defaultNamingContext[0]
}
catch {
Write-Error "Domain controller unreachable"
continue
}
if (-not $SearchBase) {
$SearchBase = $defaultNC
}
}
}
Process {
try {
if ($SSL) {
$results = @()
$domain = $defaultNC -replace 'DC=' -replace ',','.'
[Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols") | Out-Null
$searcher = New-Object -TypeName System.DirectoryServices.Protocols.LdapConnection -ArgumentList "$($Server):636"
$searcher.SessionOptions.SecureSocketLayer = $true
$searcher.SessionOptions.VerifyServerCertificate = {$true}
$searcher.SessionOptions.DomainName = $domain
$searcher.AuthType = [DirectoryServices.Protocols.AuthType]::Negotiate
if ($Credential.UserName) {
$searcher.Bind($Credential)
}
else {
$searcher.Bind()
}
if ($Properties -ne '*') {
$request = New-Object -TypeName System.DirectoryServices.Protocols.SearchRequest($SearchBase, $Filter, $SearchScope, $Properties)
}
else {
$request = New-Object -TypeName System.DirectoryServices.Protocols.SearchRequest($SearchBase, $Filter, $SearchScope)
}
$pageRequestControl = New-Object -TypeName System.DirectoryServices.Protocols.PageResultRequestControl -ArgumentList $PageSize
$request.Controls.Add($pageRequestControl) | Out-Null
$response = $searcher.SendRequest($request)
while ($true) {
$response = $searcher.SendRequest($request)
if ($response.ResultCode -eq 'Success') {
foreach ($entry in $response.Entries) {
$results += $entry
}
}
$pageResponseControl = [DirectoryServices.Protocols.PageResultResponseControl]$response.Controls[0]
if ($pageResponseControl.Cookie.Length -eq 0) {
break
}
$pageRequestControl.Cookie = $pageResponseControl.Cookie
}
}
else {
$adsPath = "LDAP://$Server/$SearchBase"
if ($Credential.UserName) {
$domainObject = New-Object DirectoryServices.DirectoryEntry($adsPath, $Credential.UserName, $Credential.GetNetworkCredential().Password)
$searcher = New-Object DirectoryServices.DirectorySearcher($domainObject)
}
else {
$searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]$adsPath)
}
$searcher.SearchScope = $SearchScope
$searcher.PageSize = $PageSize
$searcher.CacheResults = $false
$searcher.filter = $Filter
$propertiesToLoad = $Properties | ForEach-Object {$_.Split(',')}
$searcher.PropertiesToLoad.AddRange($propertiesToLoad) | Out-Null
$results = $searcher.FindAll()
}
}
catch {
Write-Error $_
continue
}
$results | Where-Object {$_} | ForEach-Object {
if (Get-Member -InputObject $_ -name "Attributes" -Membertype Properties) {
# Convert DirectoryAttribute object (LDAPS results)
$p = @{}
foreach ($a in $_.Attributes.Keys | Sort-Object) {
if (($a -eq 'objectsid') -or ($a -eq 'sidhistory') -or ($a -eq 'objectguid') -or ($a -eq 'securityidentifier') -or ($a -eq 'msds-allowedtoactonbehalfofotheridentity') -or ($a -eq 'usercertificate') -or ($a -eq 'ntsecuritydescriptor') -or ($a -eq 'logonhours')) {
$p[$a] = $_.Attributes[$a]
}
elseif ($a -eq 'dnsrecord') {
$p[$a] = ($_.Attributes[$a].GetValues([byte[]]))[0]
}
elseif (($a -eq 'whencreated') -or ($a -eq 'whenchanged')) {
$value = ($_.Attributes[$a].GetValues([byte[]]))[0]
$format = "yyyyMMddHHmmss.fZ"
$p[$a] = [datetime]::ParseExact([Text.Encoding]::UTF8.GetString($value), $format, [cultureinfo]::InvariantCulture)
}
else {
$values = @()
foreach ($v in $_.Attributes[$a].GetValues([byte[]])) {
$values += [Text.Encoding]::UTF8.GetString($v)
}
$p[$a] = $values
}
}
}
else {
$p = $_.Properties
}
$objectProperties = @{}
$p.Keys | ForEach-Object {
if (($_ -ne 'adspath') -and ($p[$_].count -eq 1)) {
$objectProperties[$_] = $p[$_][0]
}
elseif ($_ -ne 'adspath') {
$objectProperties[$_] = $p[$_]
}
}
New-Object -TypeName PSObject -Property ($objectProperties)
}
}
End {
if ($results -and -not $SSL) {
$results.dispose()
}
if ($searcher) {
$searcher.dispose()
}
}
}
Function Local:Get-LapsCredential {
Param (
[ValidateNotNullOrEmpty()]
[String]
$Server = $Env:USERDNSDOMAIN,
[Switch]
$SSL,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$Credential = [Management.Automation.PSCredential]::Empty,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$ComputerName
)
BEGIN {
if ($Credential.UserName) {
$logonToken = Invoke-UserImpersonation -Credential $Credential
}
}
PROCESS {
$lapsCredential = $null
$filter = "(&(sAMAccountType=805306369)(dnshostname=$ComputerName)(ms-MCS-AdmPwd=*))"
Get-LdapObject -Server $Server -SSL:$SSL -Filter $filter -Properties 'ms-MCS-AdmPwd' -Credential $Credential | ForEach-Object {
if ($password = $_.'ms-MCS-AdmPwd') {
$lapsPassword = ConvertTo-SecureString $password -AsPlainText -Force
# Search for local group name for SID S-1-5-32-544
$groupName = ''
$computerProvider = [ADSI] "WinNT://$ComputerName,computer"
$computerProvider.psbase.children | Where-Object { $_.psbase.schemaClassName -eq 'group' } | ForEach-Object {
$localGroup = [ADSI] $_
$groupSid = (New-Object Security.Principal.SecurityIdentifier($localGroup.InvokeGet('ObjectSID'), 0)).Value
if ($groupSid -eq 'S-1-5-32-544') {
$groupName = $localGroup.InvokeGet('Name')
break
}
}
# Search for local user name for RID 500
$lapsUsername = 'Administrator' # default value
if ($groupName) {
$groupProvider = [ADSI] "WinNT://$ComputerName/$groupName,group"
$groupProvider.psbase.Invoke('Members') | ForEach-Object {
$localUser = [ADSI] $_
$userSid = (New-Object Security.Principal.SecurityIdentifier($localUser.InvokeGet('ObjectSID'),0)).Value
if ($userSid -match '.*-500') {
$lapsUsername = $localUser.InvokeGet('Name')
break
}
}
}
$lapsCredential = New-Object Management.Automation.PSCredential ($lapsUsername, $lapsPassword)
break
}
}
}
END {
if ($logonToken) {
Invoke-RevertToSelf -TokenHandle $logonToken
}
return $lapsCredential
}
}
Function Local:Get-DelegateType {
Param (
[Type[]]
$Parameters = (New-Object Type[](0)),
[Type]
$ReturnType = [Void]
)
$domain = [AppDomain]::CurrentDomain
$dynAssembly = New-Object Reflection.AssemblyName('ReflectedDelegate')
$assemblyBuilder = $domain.DefineDynamicAssembly($dynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$moduleBuilder = $assemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$typeBuilder = $moduleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [MulticastDelegate])
$constructorBuilder = $typeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [Reflection.CallingConventions]::Standard, $Parameters)
$constructorBuilder.SetImplementationFlags('Runtime, Managed')
$methodBuilder = $typeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$methodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $typeBuilder.CreateType()
}
Function Local:Get-ProcAddress {
Param (
[Parameter(Mandatory = $True)]
[String]
$Module,
[Parameter(Mandatory = $True)]
[String]
$Procedure
)
$systemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$unsafeNativeMethods = $systemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
$getModuleHandle = $unsafeNativeMethods.GetMethod('GetModuleHandle')
$getProcAddress = $unsafeNativeMethods.GetMethod('GetProcAddress', [Type[]]@([Runtime.InteropServices.HandleRef], [String]))
$kern32Handle = $getModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$handleRef = New-Object Runtime.InteropServices.HandleRef($tmpPtr, $kern32Handle)
Write-Output $getProcAddress.Invoke($null, @([Runtime.InteropServices.HandleRef]$handleRef, $Procedure))
}
Function Local:Invoke-UserImpersonation {
Param(
[Parameter(Mandatory = $True)]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential
)
$logonUserAddr = Get-ProcAddress Advapi32.dll LogonUserA
$logonUserDelegate = Get-DelegateType @([String], [String], [String], [UInt32], [UInt32], [IntPtr].MakeByRefType()) ([Bool])
$logonUser = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($logonUserAddr, $logonUserDelegate)
$impersonateLoggedOnUserAddr = Get-ProcAddress Advapi32.dll ImpersonateLoggedOnUser
$impersonateLoggedOnUserDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$impersonateLoggedOnUser = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($impersonateLoggedOnUserAddr, $impersonateLoggedOnUserDelegate)
$logonTokenHandle = [IntPtr]::Zero
$networkCredential = $Credential.GetNetworkCredential()
$userDomain = $networkCredential.Domain
$userName = $networkCredential.UserName
if (-not $logonUser.Invoke($userName, $userDomain, $networkCredential.Password, 9, 3, [ref]$logonTokenHandle)) {
$lastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
throw "[UserImpersonation] LogonUser error: $(([ComponentModel.Win32Exception] $lastError).Message)"
}
if (-not $impersonateLoggedOnUser.Invoke($logonTokenHandle)) {
throw "[UserImpersonation] ImpersonateLoggedOnUser error: $(([ComponentModel.Win32Exception] $lastError).Message)"
}
Write-Output $logonTokenHandle
}
Function Local:Invoke-RevertToSelf {
[CmdletBinding()]
Param(
[ValidateNotNull()]
[IntPtr]
$TokenHandle
)
$closeHandleAddr = Get-ProcAddress Kernel32.dll CloseHandle
$closeHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$closeHandle = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($closeHandleAddr, $closeHandleDelegate)
$revertToSelfAddr = Get-ProcAddress Advapi32.dll RevertToSelf
$revertToSelfDelegate = Get-DelegateType @() ([Bool])
$revertToSelf = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($revertToSelfAddr, $revertToSelfDelegate)
if ($PSBoundParameters['TokenHandle']) {
$closeHandle.Invoke($TokenHandle) | Out-Null
}
if (-not $revertToSelf.Invoke()) {
$lastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
throw "[RevertToSelf] Error: $(([ComponentModel.Win32Exception] $lastError).Message)"
}
}