/
RpcFunctions.ps1
1557 lines (1478 loc) · 53.3 KB
/
RpcFunctions.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
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
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
$protseq_completer = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
@("ncalrpc", "ncacn_np", "ncacn_ip_tcp", "ncacn_http") | Where-Object { $_ -like "$wordToComplete*" }
}
<#
.SYNOPSIS
Get a list of ALPC Ports that can be opened by a specified token.
.DESCRIPTION
This cmdlet checks for all ALPC ports on the system and tries to determine if one or more specified tokens can connect to them.
If no tokens are specified then the current process token is used. This function searches handles for existing ALPC Port servers as you can't directly open the server object and just connecting might show inconsistent results.
.PARAMETER ProcessId
Specify a list of process IDs to open for their tokens.
.PARAMETER ProcessName
Specify a list of process names to open for their tokens.
.PARAMETER ProcessCommandLine
Specify a list of command lines to filter on find for the process tokens.
.PARAMETER Token
Specify a list token objects.
.PARAMETER Process
Specify a list process objects to use for their tokens.
.INPUTS
None
.OUTPUTS
NtObjectManager.Cmdlets.Accessible.CommonAccessCheckResult
.NOTES
For best results run this function as an administrator with SeDebugPrivilege available.
.EXAMPLE
Get-AccessibleAlpcPort
Get all ALPC Ports connectable by the current token.
.EXAMPLE
Get-AccessibleAlpcPort -ProcessIds 1234,5678
Get all ALPC Ports connectable by the process tokens of PIDs 1234 and 5678
#>
function Get-AccessibleAlpcPort {
Param(
[alias("ProcessIds")]
[Int32[]]$ProcessId,
[alias("ProcessNames")]
[string[]]$ProcessName,
[alias("ProcessCommandLines")]
[string[]]$ProcessCommandLine,
[alias("Tokens")]
[NtApiDotNet.NtToken[]]$Token,
[alias("Processes")]
[NtApiDotNet.NtProcess[]]$Process
)
$access = Get-NtAccessMask -AlpcPortAccess Connect -ToGenericAccess
Get-AccessibleObject -FromHandle -ProcessId $ProcessId -ProcessName $ProcessName `
-ProcessCommandLine $ProcessCommandLine -Token $Token -Process $Process -TypeFilter "ALPC Port" -AccessRights $access
}
<#
.SYNOPSIS
Gets the endpoints for a RPC interface from the local endpoint mapper or by brute force.
.DESCRIPTION
This cmdlet gets the endpoints for a RPC interface from the local endpoint mapper. Not all RPC interfaces
are registered in the endpoint mapper so it might not show. You can use the -FindAlpcPort command to try
and brute force an ALPC port for the interface.
.PARAMETER InterfaceId
The UUID of the RPC interface.
.PARAMETER InterfaceVersion
The version of the RPC interface.
.PARAMETER Server
Parsed NDR server.
.PARAMETER Binding
A RPC binding string to query all endpoints from.
.PARAMETER AlpcPort
An ALPC port name. Can contain a full path as long as the string contains \RPC Control\ (case sensitive).
.PARAMETER FindAlpcPort
Use brute force to find a valid ALPC endpoint for the interface.
.PARAMETER ProcessId
Used to find all ALPC ports in a process and get the supported interfaces.
.INPUTS
None or NtApiDotNet.Ndr.NdrRpcServerInterface
.OUTPUTS
NtApiDotNet.Win32.RpcEndpoint[]
.EXAMPLE
Get-RpcEndpoint
Get all RPC registered RPC endpoints.
.EXAMPLE
Get-RpcEndpoint $Server
Get RPC endpoints for a parsed NDR server interface.
.EXAMPLE
Get-RpcEndpoint "A57A4ED7-0B59-4950-9CB1-E600A665154F"
Get RPC endpoints for a specified interface ID ignoring the version.
.EXAMPLE
Get-RpcEndpoint "A57A4ED7-0B59-4950-9CB1-E600A665154F" "1.0"
Get RPC endpoints for a specified interface ID and version.
.EXAMPLE
Get-RpcEndpoint "A57A4ED7-0B59-4950-9CB1-E600A665154F" "1.0" -FindAlpcPort
Get ALPC RPC endpoints for a specified interface ID and version by brute force.
.EXAMPLE
Get-RpcEndpoint -Binding "ncalrpc:[RPC_PORT]"
Get RPC endpoints for exposed over ncalrpc with name RPC_PORT.
.EXAMPLE
Get-RpcEndpoint -AlpcPort "RPC_PORT"
Get RPC endpoints for exposed over ALPC with name RPC_PORT.
.EXAMPLE
Get-RpcEndpoint -ProcessId 1234
Get RPC endpoints for exposed over ALPC for the process 1234.
#>
function Get-RpcEndpoint {
[CmdletBinding(DefaultParameterSetName = "All")]
Param(
[parameter(Mandatory, Position = 0, ParameterSetName = "FromId")]
[parameter(Mandatory, Position = 0, ParameterSetName = "FromIdAndVersion")]
[Guid]$InterfaceId,
[parameter(Mandatory, Position = 1, ParameterSetName = "FromIdAndVersion")]
[Version]$InterfaceVersion,
[parameter(Mandatory, ParameterSetName = "FromServer", ValueFromPipeline)]
[NtApiDotNet.Ndr.NdrRpcServerInterface]$Server,
[parameter(Mandatory, ParameterSetName = "FromBinding")]
[string]$Binding,
[parameter(Mandatory, ParameterSetName = "FromAlpc")]
[string]$AlpcPort,
[parameter(Mandatory, ParameterSetName = "FromProcessId")]
[alias("pid")]
[int]$ProcessId,
[parameter(ParameterSetName = "FromIdAndVersion")]
[parameter(ParameterSetName = "FromServer")]
[switch]$FindAlpcPort,
[parameter(ParameterSetName = "All")]
[parameter(ParameterSetName = "FromId")]
[parameter(ParameterSetName = "FromIdAndVersion")]
[parameter(ParameterSetName = "FromRpcClient")]
[string]$SearchBinding = "",
[parameter(ParameterSetName = "All")]
[parameter(ParameterSetName = "FromId")]
[parameter(ParameterSetName = "FromIdAndVersion")]
[parameter(ParameterSetName = "FromRpcClient")]
[string[]]$ProtocolSequence = @(),
[parameter(Mandatory, ParameterSetName = "FromRpcClient")]
[NtApiDotNet.Win32.Rpc.RpcClientBase]$Client
)
PROCESS {
$eps = switch ($PsCmdlet.ParameterSetName) {
"All" {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpoints($SearchBinding)
}
"FromId" {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpoints($SearchBinding, $InterfaceId)
}
"FromIdAndVersion" {
if ($FindAlpcPort) {
[NtApiDotNet.Win32.RpcEndpointMapper]::FindAlpcEndpointForInterface($InterfaceId, $InterfaceVersion)
}
else {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpoints($SearchBinding, $InterfaceId, $InterfaceVersion)
}
}
"FromServer" {
if ($FindAlpcPort) {
[NtApiDotNet.Win32.RpcEndpointMapper]::FindAlpcEndpointForInterface($Server.InterfaceId, $Server.InterfaceVersion)
}
else {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpoints($Server)
}
}
"FromBinding" {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpointsForBinding($Binding)
}
"FromAlpc" {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpointsForAlpcPort($AlpcPort)
}
"FromRpcClient" {
[NtApiDotNet.Win32.RpcEndpointMapper]::QueryEndpoints($SearchBinding, $Client.InterfaceId, $Client.InterfaceVersion)
}
"FromProcessId" {
(Get-RpcAlpcServer -ProcessId $ProcessId).Endpoints
}
}
if ($ProtocolSequence.Count -gt 0) {
$eps = $eps | Where-Object {$_.ProtocolSequence -in $ProtocolSequence}
}
$eps | Write-Output
}
}
Register-ArgumentCompleter -CommandName Get-RpcEndpoint -ParameterName ProtocolSequence -ScriptBlock $protseq_completer
<#
.SYNOPSIS
Get the RPC servers from a DLL.
.DESCRIPTION
This cmdlet parses the RPC servers from a DLL. Note that in order to parse 32 bit DLLs you must run this module in 32 bit PowerShell.
.PARAMETER FullName
The path to the DLL.
.PARAMETER DbgHelpPath
Specify path to a dbghelp DLL to use for symbol resolving. This should be ideally the dbghelp from debugging tool for Windows
which will allow symbol servers however you can use the system version if you just want to pull symbols locally.
.PARAMETER SymbolPath
Specify path for the symbols. If not specified it will first use the _NT_SYMBOL_PATH environment variable then use the
default of 'srv*https://msdl.microsoft.com/download/symbols'
.PARAMETER AsText
Return the results as text rather than objects.
.PARAMETER RemoveComments
When outputing as text remove comments from the output.
.PARAMETER ParseClients
Also parse client interface information, otherwise only servers are returned.
.PARAMETER IgnoreSymbols
Don't resolve any symbol information.
.PARAMETER SerializedPath
Path to a serialized representation of the RPC servers.
.PARAMETER ResolveStructureNames
If private symbols available try and resolve the names of structures and parameters.
.PARAMETER SymSrvFallback
Specify to use a built-in fallback for symbol server resolving when using the system dbghelp DLL. You also need to specify a local cache directory in SymbolPath.
.PARAMETER ProcessId
Specify a process to extract the RPC servers from. This parses all the modules in a process for any available servers.
.INPUTS
string[] List of paths to DLLs.
.OUTPUTS
RpcServer[] The parsed RPC servers.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll
Get the list of RPC servers from rpcss.dll.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll -AsText
Get the list of RPC servers from rpcss.dll, return it as text.
.EXAMPLE
Get-ChildItem c:\windows\system32\*.dll | Get-RpcServer
Get the list of RPC servers from all DLLs in system32, return it as text.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll -DbgHelpPath c:\windbg\x64\dbghelp.dll
Get the list of RPC servers from rpcss.dll, specifying a different DBGHELP for symbol resolving.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll -SymbolPath c:\symbols
Get the list of RPC servers from rpcss.dll, specifying a different symbol path.
.EXAMPLE
Get-RpcServer -SerializedPath rpc.bin
Get the list of RPC servers from the serialized file rpc.bin.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll -SymSrvFallback -SymbolPath c:\symbols
Get the list of RPC servers from rpcss.dll, use symbol server fallback with c:\symbols as the cache directory.
#>
function Get-RpcServer {
[CmdletBinding(DefaultParameterSetName = "FromDll")]
Param(
[parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = "FromDll")]
[alias("Path")]
[string]$FullName,
[parameter(Mandatory, ParameterSetName = "FromSerialized")]
[string]$SerializedPath,
[parameter(Mandatory, ParameterSetName = "FromProcessId")]
[alias("pid")]
[int]$ProcessId,
[parameter(ParameterSetName = "FromDll")]
[parameter(ParameterSetName = "FromProcessId")]
[string]$DbgHelpPath,
[parameter(ParameterSetName = "FromDll")]
[parameter(ParameterSetName = "FromProcessId")]
[string]$SymbolPath,
[parameter(ParameterSetName = "FromDll")]
[switch]$ParseClients,
[parameter(ParameterSetName = "FromDll")]
[parameter(ParameterSetName = "FromProcessId")]
[switch]$IgnoreSymbols,
[parameter(ParameterSetName = "FromDll")]
[parameter(ParameterSetName = "FromProcessId")]
[switch]$ResolveStructureNames,
[parameter(ParameterSetName = "FromDll")]
[parameter(ParameterSetName = "FromProcessId")]
[switch]$SymSrvFallback,
[switch]$AsText,
[switch]$RemoveComments
)
BEGIN {
if ($DbgHelpPath -eq "") {
$DbgHelpPath = $Script:GlobalDbgHelpPath
}
if ($SymbolPath -eq "") {
$SymbolPath = $env:_NT_SYMBOL_PATH
if ($SymbolPath -eq "") {
$SymbolPath = $Script:GlobalSymbolPath
}
}
$ParserFlags = [NtApiDotNet.Win32.RpcServerParserFlags]::None
if ($ParseClients) {
$ParserFlags = $ParserFlags -bor [NtApiDotNet.Win32.RpcServerParserFlags]::ParseClients
}
if ($IgnoreSymbols) {
$ParserFlags = $ParserFlags -bor [NtApiDotNet.Win32.RpcServerParserFlags]::IgnoreSymbols
}
if ($ResolveStructureNames) {
$ParserFlags = $ParserFlags -bor [NtApiDotNet.Win32.RpcServerParserFlags]::ResolveStructureNames
}
if ($SymSrvFallback) {
$ParserFlags = $ParserFlags -bor [NtApiDotNet.Win32.RpcServerParserFlags]::SymSrvFallback
}
}
PROCESS {
try {
$servers = switch($PSCmdlet.ParameterSetName) {
"FromDll" {
$FullName = Resolve-Path -LiteralPath $FullName -ErrorAction Stop
Write-Progress -Activity "Parsing RPC Servers" -CurrentOperation "$FullName"
[NtApiDotNet.Win32.RpcServer]::ParsePeFile($FullName, $DbgHelpPath, $SymbolPath, $ParserFlags)
}
"FromSerialized" {
$FullName = Resolve-Path -LiteralPath $SerializedPath -ErrorAction Stop
Use-NtObject($stm = [System.IO.File]::OpenRead($FullName)) {
while ($stm.Position -lt $stm.Length) {
[NtApiDotNet.Win32.RpcServer]::Deserialize($stm) | Write-Output
}
}
}
"FromProcessId" {
$proc = Get-Process -PID $ProcessId
if ($null -eq $proc.SafeHandle) {
throw "Can't open process $ProcessId"
}
$proc.Modules |
% {
Get-RpcServer -FullName $_.FileName -DbgHelpPath $DbgHelpPath -SymbolPath $SymbolPath `
-IgnoreSymbols:$IgnoreSymbols -ResolveStructureNames:$ResolveStructureNames -SymSrvFallback:$SymSrvFallback
}
}
}
if ($null -ne $servers) {
if ($AsText) {
foreach ($server in $servers) {
$text = $server.FormatAsText($RemoveComments)
Write-Output $text
}
}
else {
Write-Output $servers
}
}
}
catch {
Write-Error $_
}
}
}
<#
.SYNOPSIS
Set a list RPC servers to a file for storage.
.DESCRIPTION
This cmdlet serializes a list of RPC servers to a file. This can be restored using Get-RpcServer -SerializedPath.
.PARAMETER Path
The path to the output file.
.PARAMETER Server
The list of servers to serialize.
.INPUTS
RpcServer[] List of paths to DLLs.
.OUTPUTS
None
.EXAMPLE
Set-RpcServer -Server $server -Path rpc.bin
Serialize servers to file rpc.bin.
#>
function Set-RpcServer {
Param(
[parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
[NtApiDotNet.Win32.RpcServer[]]$Server,
[parameter(Mandatory = $true, Position = 1)]
[string]$Path
)
BEGIN {
"" | Set-Content -Path $Path
$Path = Resolve-Path -LiteralPath $Path -ErrorAction Stop
$stm = [System.IO.File]::Create($Path)
}
PROCESS {
try {
foreach ($s in $Server) {
$s.Serialize($stm)
}
}
catch {
Write-Error $_
}
}
END {
$stm.Close()
}
}
<#
.SYNOPSIS
Format the RPC servers as text.
.DESCRIPTION
This cmdlet formats a list of RPC servers as text.
.PARAMETER RpcServer
The RPC servers to format.
.PARAMETER RemoveComments
When outputing as text remove comments from the output.
.PARAMETER CppFormat
Format output in C++ pseudo syntax rather than C++.
.INPUTS
RpcServer[] The RPC servers to format.
.OUTPUTS
string[] The formatted RPC servers.
.EXAMPLE
Format-RpcServer $rpc
Format list of RPC servers in $rpc.
.EXAMPLE
Format-RpcServer $rpc -RemoveComments
Format list of RPC servers in $rpc without comments.
.EXAMPLE
Get-RpcServer c:\windows\system32\rpcss.dll | Format-RpcServer
Get the list of RPC servers from rpcss.dll and format them.
#>
function Format-RpcServer {
[CmdletBinding()]
Param(
[parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
[NtApiDotNet.Win32.RpcServer[]]$RpcServer,
[switch]$RemoveComments,
[switch]$CppFormat
)
PROCESS {
foreach ($server in $RpcServer) {
$server.FormatAsText($RemoveComments, $CppFormat) | Write-Output
}
}
}
<#
.SYNOPSIS
Gets a list of ALPC RPC servers.
.DESCRIPTION
This cmdlet gets a list of ALPC RPC servers. This relies on being able to access the list of ALPC ports in side a process so might need elevated privileges.
.PARAMETER ProcessId
The ID of a process to query for ALPC servers.
.PARAMETER AlpcPort
The path to the ALPC port to query.
.INPUTS
None
.OUTPUTS
NtApiDotNet.Win32.RpcAlpcServer[]
.EXAMPLE
Get-RpcAlpcServer
Get all ALPC RPC servers.
.EXAMPLE
Get-RpcAlpcServer -ProcessId 1234
Get all ALPC RPC servers in process ID 1234.
.EXAMPLE
Get-RpcAlpcServer -AlpcPort srvsvc
Get the ALPC RPC servers for the srvsvc ALPC port. Needs Windows 10 19H1 and above to work.
#>
function Get-RpcAlpcServer {
[CmdletBinding(DefaultParameterSetName = "All")]
Param(
[parameter(Mandatory, Position = 0, ParameterSetName = "FromProcessId")]
[int]$ProcessId,
[parameter(Mandatory, ParameterSetName = "FromAlpc")]
[string]$AlpcPort
)
Set-NtTokenPrivilege SeDebugPrivilege | Out-Null
switch ($PsCmdlet.ParameterSetName) {
"All" {
[NtApiDotNet.Win32.RpcAlpcServer]::GetAlpcServers()
}
"FromProcessId" {
[NtApiDotNet.Win32.RpcAlpcServer]::GetAlpcServers($ProcessId)
}
"FromAlpc" {
[NtApiDotNet.Win32.RpcAlpcServer]::GetAlpcServer($AlpcPort)
}
}
}
<#
.SYNOPSIS
Get a RPC client object based on a parsed RPC server.
.DESCRIPTION
This cmdlet creates a new RPC client from a parsed RPC server. The client object contains methods
to call RPC methods. The client starts off disconnected. You need to pass the client to Connect-RpcClient to
connect to the server. If you specify an interface ID and version then a generic client will be created which
allows simple calls to be made without requiring the NDR data.
.PARAMETER Server
Specify the RPC server to base the client on.
.PARAMETER NamespaceName
Specify the name of the compiled namespace for the client.
.PARAMETER ClientName
Specify the class name of the compiled client.
.PARAMETER IgnoreCache
Specify to ignore the compiled client cache and regenerate the source code.
.PARAMETER InterfaceId
Specify the interface ID for a generic client.
.PARAMETER InterfaceVersion
Specify the interface version for a generic client.
.PARAMETER Provider
Specify a Code DOM provider. Defaults to C#.
.PARAMETER Flags
Specify optional flags for the built client class.
.PARAMETER EnableDebugging
Specify to enable debugging on the compiled code.
.INPUTS
None
.OUTPUTS
NtApiDotNet.Win32.Rpc.RpcClientBase
.EXAMPLE
Get-RpcClient -Server $Server
Create a new RPC client from a parsed RPC server.
#>
function Get-RpcClient {
[CmdletBinding(DefaultParameterSetName = "FromServer")]
Param(
[parameter(Mandatory, Position = 0, ParameterSetName = "FromServer", ValueFromPipeline)]
[NtApiDotNet.Win32.RpcServer]$Server,
[parameter(ParameterSetName = "FromServer")]
[string]$NamespaceName,
[parameter(ParameterSetName = "FromServer")]
[string]$ClientName,
[parameter(ParameterSetName = "FromServer")]
[switch]$IgnoreCache,
[parameter(Mandatory, Position = 0, ParameterSetName = "FromIdAndVersion")]
[string]$InterfaceId,
[parameter(Mandatory, Position = 1, ParameterSetName = "FromIdAndVersion")]
[Version]$InterfaceVersion,
[parameter(ParameterSetName = "FromServer")]
[System.CodeDom.Compiler.CodeDomProvider]$Provider,
[parameter(ParameterSetName = "FromServer")]
[NtApiDotNet.Win32.Rpc.RpcClientBuilderFlags]$Flags = "GenerateConstructorProperties, StructureReturn, HideWrappedMethods, UnsignedChar, NoNamespace, MarshalPipesAsArrays",
[switch]$EnableDebugging
)
BEGIN {
if (Get-IsPSCore) {
if ($null -ne $Provider) {
Write-Warning "PowerShell Core doesn't support arbitrary providers. Using in-built C#."
}
$Provider = New-Object NtObjectManager.Utils.CoreCSharpCodeProvider
}
}
PROCESS {
if ($PSCmdlet.ParameterSetName -eq "FromServer") {
$args = [NtApiDotNet.Win32.Rpc.RpcClientBuilderArguments]::new();
$args.NamespaceName = $NamespaceName
$args.ClientName = $ClientName
$args.Flags = $Flags
$args.EnableDebugging = $EnableDebugging
[NtApiDotNet.Win32.Rpc.RpcClientBuilder]::CreateClient($Server, $args, $IgnoreCache, $Provider)
}
else {
[NtApiDotNet.Win32.RpcClient]::new($InterfaceId, $InterfaceVersion)
}
}
}
<#
.SYNOPSIS
Connects a RPC client to an endpoint.
.DESCRIPTION
This cmdlet connects a RPC client to an endpoint. You can specify what transport to use based on the protocol sequence.
.PARAMETER Client
Specify the RPC client to connect.
.PARAMETER ProtocolSequence
Specify the RPC protocol sequence this client will connect through.
.PARAMETER EndpointPath
Specify the endpoint string. If not specified this will lookup the endpoint from the endpoint mapper.
.PARAMETER NetworkAddress
Specify the network address. If not specified the local system will be used.
.PARAMETER SecurityQualityOfService
Specify the security quality of service for the connection.
.PARAMETER Credentials
Specify user credentials for the RPC client authentication.
.PARAMETER ServicePrincipalName
Specify service principal name for the RPC client authentication.
.PARAMETER AuthenticationLevel
Specify authentication level for the RPC client authentication.
.PARAMETER AuthenticationType
Specify authentication type for the RPC client authentication.
.PARAMETER AuthenticationCapabilities
Specify authentication capabilities for the RPC client authentication.
.PARAMETER PassThru
Specify to the pass the client object to the output.
.PARAMETER FindAlpcPort
Specify to search for an ALPC port for the RPC client.
.PARAMETER Force
Specify to for the client to connect even if the client is already connected to another transport.
.INPUTS
NtApiDotNet.Win32.Rpc.RpcClientBase[]
.OUTPUTS
NtApiDotNet.Win32.Rpc.RpcClientBase[]
.EXAMPLE
Connect-RpcClient -Client $Client
Connect an RPC ALPC client, looking up the path using the endpoint mapper.
.EXAMPLE
Connect-RpcClient -Client $Client -EndpointPath "\RPC Control\ABC"
Connect an RPC ALPC client with an explicit path.
.EXAMPLE
Connect-RpcClient -Client $Client -SecurityQualityOfService $(New-NtSecurityQualityOfService -ImpersonationLevel Anonymous)
Connect an RPC ALPC client with anonymous impersonation level.
.EXAMPLE
Connect-RpcClient -Client $Client -ProtocolSequence "ncalrpc"
Connect an RPC ALPC client from a specific protocol sequence.
.EXAMPLE
Connect-RpcClient -Client $Client -Endpoint $ep
Connect an RPC client to a specific endpoint.
.EXAMPLE
Connect-RpcClient -Client $Client -FindAlpcPort
Connect an RPC ALPC client, looking up the path using brute force.
#>
function Connect-RpcClient {
[CmdletBinding(DefaultParameterSetName = "FromProtocol")]
Param(
[parameter(Mandatory, Position = 0, ValueFromPipeline)]
[NtApiDotNet.Win32.Rpc.RpcClientBase]$Client,
[parameter(Position = 1, ParameterSetName = "FromProtocol")]
[string]$EndpointPath,
[parameter(ParameterSetName = "FromProtocol")]
[string]$ProtocolSequence = "ncalrpc",
[parameter(ParameterSetName = "FromProtocol")]
[string]$NetworkAddress,
[parameter(Position = 1, Mandatory, ParameterSetName = "FromEndpoint")]
[NtApiDotNet.Win32.RpcEndpoint]$Endpoint,
[parameter(Mandatory, ParameterSetName = "FromFindEndpoint")]
[switch]$FindAlpcPort,
[parameter(ParameterSetName = "FromBindingString")]
[string]$StringBinding,
[NtApiDotNet.SecurityQualityOfService]$SecurityQualityOfService,
[NtApiDotNet.Win32.Security.Authentication.AuthenticationCredentials]$Credentials,
[string]$ServicePrincipalName,
[NtApiDotNet.Win32.Rpc.Transport.RpcAuthenticationLevel]$AuthenticationLevel = "None",
[NtApiDotNet.Win32.Rpc.Transport.RpcAuthenticationType]$AuthenticationType = "None",
[NtApiDotNet.Win32.Rpc.Transport.RpcAuthenticationCapabilities]$AuthenticationCapabilities = "None",
[switch]$PassThru,
[switch]$Force
)
BEGIN {
$security = New-Object NtApiDotNet.Win32.Rpc.Transport.RpcTransportSecurity
$security.SecurityQualityOfService = $SecurityQualityOfService
$security.Credentials = $Credentials
$security.ServicePrincipalName = $ServicePrincipalName
$security.AuthenticationLevel = $AuthenticationLevel
$security.AuthenticationType = $AuthenticationType
$security.AuthenticationCapabilities = $AuthenticationCapabilities
}
PROCESS {
if ($Force) {
Disconnect-RpcClient -Client $Client
}
switch ($PSCmdlet.ParameterSetName) {
"FromProtocol" {
$Client.Connect($ProtocolSequence, $EndpointPath, $NetworkAddress, $security)
}
"FromEndpoint" {
$Client.Connect($Endpoint, $security)
}
"FromFindEndpoint" {
foreach ($ep in $(Get-ChildItem "NtObject:\RPC Control")) {
try {
$name = $ep.Name
Write-Progress -Activity "Finding ALPC Endpoint" -CurrentOperation "$name"
$Client.Connect("ncalrpc", $name, $security)
}
catch {
Write-Information $_
}
}
}
"FromBindingString" {
$Client.Connect($StringBinding, $security)
}
}
if ($PassThru) {
$Client | Write-Output
}
}
}
Register-ArgumentCompleter -CommandName Connect-RpcClient -ParameterName ProtocolSequence -ScriptBlock $protseq_completer
<#
.SYNOPSIS
Disconnect an RPC client.
.DESCRIPTION
This cmdlet disconnects a RPC client from an endpoint.
.PARAMETER Client
Specify the RPC client to disconnect.
.PARAMETER PassThru
Specify to the pass the client object to the output.
.INPUTS
NtApiDotNet.Win32.Rpc.RpcClientBase[]
.OUTPUTS
NtApiDotNet.Win32.Rpc.RpcClientBase[]
.EXAMPLE
Disconnect-RpcClient -Client $Client
Disconnect an RPC ALPC client.
#>
function Disconnect-RpcClient {
[CmdletBinding()]
Param(
[parameter(Mandatory, Position = 0, ValueFromPipeline)]
[NtApiDotNet.Win32.Rpc.RpcClientBase]$Client,
[switch]$PassThru
)
PROCESS {
$Client.Disconnect()
if ($PassThru) {
$Client | Write-Output
}
}
}
<#
.SYNOPSIS
Format a RPC client as source code based on a parsed RPC server.
.DESCRIPTION
This cmdlet gets source code for a RPC client from a parsed RPC server.
.PARAMETER Server
Specify the RPC server to base the client on.
.PARAMETER NamespaceName
Specify the name of the compiled namespace for the client.
.PARAMETER ClientName
Specify the class name of the compiled client.
.PARAMETER Flags
Specify to flags for the source creation.
.PARAMETER Provider
Specify a Code DOM provider. Defaults to C#.
.PARAMETER Options
Specify optional options for the code generation if Provider is also specified.
.PARAMETER OutputPath
Specify optional output directory to write formatted client.
.PARAMETER GroupByName
Specify when outputting to a directory to group by the name of the server executable.
.INPUTS
None
.OUTPUTS
string
.EXAMPLE
Format-RpcClient -Server $Server
Get the source code for a RPC client from a parsed RPC server.
.EXAMPLE
$servers | Format-RpcClient
Get the source code for RPC clients from a list of parsed RPC servers.
.EXAMPLE
$servers | Format-RpcClient -OutputPath rpc_output
Get the source code for RPC clients from a list of parsed RPC servers and output as separate source code files.
#>
function Format-RpcClient {
[CmdletBinding()]
Param(
[parameter(Mandatory, Position = 0, ValueFromPipeline)]
[NtApiDotNet.Win32.RpcServer[]]$Server,
[string]$NamespaceName,
[string]$ClientName,
[NtApiDotNet.Win32.Rpc.RpcClientBuilderFlags]$Flags = 0,
[System.CodeDom.Compiler.CodeDomProvider]$Provider,
[System.CodeDom.Compiler.CodeGeneratorOptions]$Options,
[string]$OutputPath,
[switch]$GroupByName
)
BEGIN {
$file_ext = "cs"
if ($null -ne $Provider) {
$file_ext = $Provider.FileExtension
}
if ("" -ne $OutputPath) {
mkdir $OutputPath -ErrorAction Ignore | Out-Null
}
}
PROCESS {
$args = [NtApiDotNet.Win32.Rpc.RpcClientBuilderArguments]::new();
$args.NamespaceName = $NamespaceName
$args.ClientName = $ClientName
$args.Flags = $Flags
foreach ($s in $Server) {
$src = if ($null -eq $Provider) {
[NtApiDotNet.Win32.Rpc.RpcClientBuilder]::BuildSource($s, $args)
}
else {
[NtApiDotNet.Win32.Rpc.RpcClientBuilder]::BuildSource($s, $args, $Provider, $Options)
}
if ("" -eq $OutputPath) {
$src | Write-Output
}
else {
if ($GroupByName) {
$path = Join-Path -Path $OutputPath -ChildPath $s.Name.ToLower()
mkdir $path -ErrorAction Ignore | Out-Null
} else {
$path = $OutputPath
}
$path = Join-Path -Path $path -ChildPath "$($s.InterfaceId)_$($s.InterfaceVersion).$file_ext"
$src | Set-Content -Path $path
}
}
}
}
<#
.SYNOPSIS
Format RPC complex types to an encoder/decoder source code file.
.DESCRIPTION
This cmdlet gets source code for encoding and decoding RPC complex types.
.PARAMETER ComplexType
Specify the list of complex types to format.
.PARAMETER Server
Specify the server containing the list of complex types to format.
.PARAMETER NamespaceName
Specify the name of the compiled namespace for the client.
.PARAMETER EncoderName
Specify the class name of the encoder.
.PARAMETER DecoderName
Specify the class name of the decoder.
.PARAMETER Provider
Specify a Code DOM provider. Defaults to C#.
.PARAMETER Options
Specify optional options for the code generation if Provider is also specified.
.PARAMETER Pointer
Specify to always wrap complex types in an unique pointer.
.INPUTS
None
.OUTPUTS
string
.EXAMPLE
Format-RpcComplexType -Server $Server
Get the source code for RPC complex types client from a parsed RPC server.
.EXAMPLE
Format-RpcComplexType -ComplexType $ComplexTypes
Get the source code for RPC complex types client from a list of types.
#>
function Format-RpcComplexType {
[CmdletBinding(DefaultParameterSetName = "FromTypes")]
Param(
[parameter(Mandatory, Position = 0, ParameterSetName = "FromTypes")]
[NtApiDotNet.Ndr.NdrComplexTypeReference[]]$ComplexType,
[parameter(Mandatory, Position = 0, ParameterSetName = "FromServer")]
[NtApiDotNet.Win32.RpcServer]$Server,
[string]$NamespaceName,
[string]$EncoderName,
[string]$DecoderName,
[System.CodeDom.Compiler.CodeDomProvider]$Provider,
[System.CodeDom.Compiler.CodeGeneratorOptions]$Options,
[switch]$Pointer
)
PROCESS {
$types = switch ($PsCmdlet.ParameterSetName) {
"FromTypes" { $ComplexType }
"FromServer" { $Server.ComplexTypes }
}
if ($null -eq $Provider) {
[NtApiDotNet.Win32.Rpc.RpcClientBuilder]::BuildSource([NtApiDotNet.Ndr.NdrComplexTypeReference[]]$types, $EncoderName, $DecoderName, $NamespaceName, $Pointer) | Write-Output
}
else {
[NtApiDotNet.Win32.Rpc.RpcClientBuilder]::BuildSource([NtApiDotNet.Ndr.NdrComplexTypeReference[]]$types, $EncoderName, $DecoderName, $NamespaceName, $Pointer, $Provider, $Options) | Write-Output
}
}
}
<#
.SYNOPSIS
Get a new RPC context handle.
.DESCRIPTION
This cmdlet creates a new RPC context handle for calling RPC APIs.
.PARAMETER Uuid
The UUID for the context handle.
.PARAMETER Attributes
The attribute flags for the context handle.
.INPUTS
None
.OUTPUTS
NtApiDotNet.Ndr.NdrContextHandle
.EXAMPLE
New-RpcContextHandle
Creates a new RPC context handle.
#>
function New-RpcContextHandle {
param(
[guid]$Uuid = [guid]::Empty,
[int]$Attributes = 0
)
[NtApiDotNet.Ndr.Marshal.NdrContextHandle]::new($Attributes, $Uuid)
}
<#
.SYNOPSIS
Get an RPC string binding from its parts.
.DESCRIPTION
This cmdlet gets an RPC string binding based on its component parts.
.PARAMETER ProtocolSequence
Specify the RPC protocol sequence .
.PARAMETER Endpoint
Specify the endpoint string.
.PARAMETER NetworkAddress
Specify the network address.
.PARAMETER ObjectUuid
Specify the object UUID.
.PARAMETER Options
Specify the options.
.INPUTS
None
.OUTPUTS
string
.EXAMPLE
Get-RpcStringBinding --ProtocolSequence "ncalrpc"
Connect an RPC ALPC string binding from a specific protocol sequence.
#>
function Get-RpcStringBinding {
[CmdletBinding(DefaultParameterSetName = "FromProtocol")]
Param(
[parameter(Mandatory, Position = 0)]
[string]$ProtocolSequence,
[parameter(Position = 1)]
[string]$Endpoint,
[parameter(Position = 2)]
[string]$NetworkAddress,
[parameter(Position = 3)]
[Guid]$ObjectUuid = [guid]::Empty,
[parameter(Position = 4)]
[string]$Options
)
$objuuid_str = ""
if ($ObjectUuid -ne [guid]::Empty) {
$objuuid_str = $ObjectUuid.ToString()
}
[NtApiDotNet.Win32.Rpc.RpcUtils]::ComposeStringBinding($objuuid_str, $ProtocolSequence, $NetworkAddress, $Endpoint, $Options)
}
Register-ArgumentCompleter -CommandName Get-RpcStringBinding -ParameterName ProtocolSequence -ScriptBlock $protseq_completer
<#
.SYNOPSIS
Creates a NDR parser for a process.
.DESCRIPTION
This cmdlet creates a new NDR parser for the given process.
.PARAMETER Process
The process to create the NDR parser on. If not specified then the current process is used.
.PARAMETER SymbolResolver
Specify a symbol resolver for the parser. Note that this should be a resolver for the same process as we're parsing.
.PARAMETER ParserFlags
Specify flags which affect the parsing operation.
.OUTPUTS
NtApiDotNet.Ndr.NdrParser - The NDR parser.
.EXAMPLE
$ndr = New-NdrParser
Get an NDR parser for the current process.
.EXAMPLE
New-NdrParser -Process $p -SymbolResolver $resolver
Get an NDR parser for a specific process with a known resolver.
#>
function New-NdrParser {
Param(
[NtApiDotNet.NtProcess]$Process,
[NtApiDotNet.Win32.ISymbolResolver]$SymbolResolver,
[NtApiDotNet.Ndr.NdrParserFlags]$ParserFlags = 0
)
[NtApiDotNet.Ndr.NdrParser]::new($Process, $SymbolResolver, $ParserFlags)
}
function Convert-HashTableToIidNames {
Param(
[Hashtable]$IidToName,
[NtApiDotNet.Ndr.NdrComProxyDefinition[]]$Proxy
)
$dict = [System.Collections.Generic.Dictionary[Guid, string]]::new()
if ($null -ne $IidToName) {
foreach ($pair in $IidToName.GetEnumerator()) {
$guid = [Guid]::new($pair.Key)
$dict.Add($guid, $pair.Value)
}
}