-
Notifications
You must be signed in to change notification settings - Fork 40
/
DVS.psm1
4562 lines (3941 loc) · 180 KB
/
DVS.psm1
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
<#
License: GPL v3
Author: Nimrod Levy (https://twitter.com/el3ct71k)
Disclaimer:
This tool is for testing and educational purposes only.
Any other usage for this code is not allowed. Use at your own risk.
The author or any Internet provider bears NO responsibility for misuse of this tool.
By using this you accept the fact that any damage caused by the use of this tool is your responsibility.
#>
$global:debug = $false # When debug is on, youll see the communication between the namedpipe server with our namedpipe client
$global:NamedPipe = "DVS" # Namedpipe name
$global:NamedpipeResponseTimeout = 5 # Namedpipe communication timeout
$global:converter = New-Object System.Management.ManagementClass Win32_SecurityDescriptorHelper # Security Descriptor converter
$global:SleepMilisecondsTime = 50 # How long time to sleep until get response
# If the function contains THESE SPECIFIC VARIANTS ONLY, assert the function as not vulnerable
# Note: Don't use spaces, in the checking process, the tool will remove spaces from the function arguments
$global:nonVulnerableArguments = @("int", "uint", "ushort", "ulong", "bool", "doublevalue", "longvalue", "intmonths", "intvalue", "longvalue")
<# Access mask calculation:
Execute Rights: 1
Local Launch/Access: 2
Remote Launch/Access: 4
Local Activation: 8
Remote Activation: 16
Reference: https://docs.microsoft.com/en-us/windows/win32/com/access-control-lists-for-com
#>
# DACL AccessMask
$COMExecutePerm = 1
$LocalCOMLaunchOrAccessPerm = 2
$RemoteCOMLaunchOrAccessPerm = 4
$LocalCOMActivationPerm = 8
$RemoteCOMActivationPerm = 16
$FullControl = 983103
# Required Remote launch and activation rights for a DCOM object.
$global:RemoteLaunchAndActivationRights = @(
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $RemoteCOMActivationPerm),
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $RemoteCOMActivationPerm + $LocalCOMLaunchOrAccessPerm),
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $RemoteCOMActivationPerm + $LocalCOMActivationPerm),
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $RemoteCOMActivationPerm + $LocalCOMActivationPerm + $LocalCOMLaunchOrAccessPerm),
$FullControl
);
$global:LocalLaunchAndActivationRights = @(
($COMExecutePerm + $LocalCOMLaunchOrAccessPerm + $LocalCOMActivationPerm),
($COMExecutePerm + $LocalCOMLaunchOrAccessPerm + $LocalCOMActivationPerm + $RemoteCOMLaunchOrAccessPerm),
($COMExecutePerm + $LocalCOMLaunchOrAccessPerm + $LocalCOMActivationPerm + $RemoteCOMActivationPerm),
($COMExecutePerm + $LocalCOMLaunchOrAccessPerm + $LocalCOMActivationPerm + $RemoteCOMActivationPerm + $RemoteCOMLaunchOrAccessPerm),
$FullControl
);
# Required Access rights for a DCOM object.
$global:RemoteAccessRights = @(
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm),
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $LocalCOMLaunchOrAccessPerm),
$FullControl
)
$global:LocalAccessRights = @(
($COMExecutePerm + $LocalCOMLaunchOrAccessPerm),
($COMExecutePerm + $RemoteCOMLaunchOrAccessPerm + $LocalCOMLaunchOrAccessPerm),
$FullControl
)
# Log, results and state file locations
$global:LogFileName = "$($(Get-Location).Path)\log.txt"
$global:ResultsFileName = "$($(Get-Location).Path)\results.csv"
$global:ScanStateFileName = "$($(Get-Location).Path)\restore.dvs"
# Regex for fetch argument list of function
[regex]$global:regexFunctionArgs = "\(.*\)"
# Regex for clsids validation
[regex]$global:guidRegex = '(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$'
# Regex to identify IP address
[regex]$global:IPRegex = '^(?:(?:(?:\d{0,3}\.){3})\d)$'
# Collects all builtin functions in order to skip them
$global:NativeFunctions = @(
[System.String](""), [System.Int32](1), [System.Boolean]($true),
[System.Array](1,2), @{"A"="B"}, (New-Object PSObject)
)|ForEach {
$_.psobject.Members|ForEach {
%{$_.Name}
}
}| Select -Unique
# General function list
Function Write-Log {
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Mandatory=$true)]
[ValidateSet("INFO","VERBOSE","ERROR")]
[String]$Level,
[switch]$forceVerbose,
[Parameter(Mandatory=$True)]
$Message
)
$Line = "$((Get-Date).toString("yyyy/MM/dd HH:mm:ss")) $($Level) $($Message)";
if($Level -eq "VERBOSE" -or $forceVerbose) { # output only if write-log on verbose mode.
if($VerbosePreference -eq "Continue") {
if($Level -eq "ERROR") {
Write-Warning $Line
} else {
Write-Verbose $Line
}
$global:LogStream.WriteLine($Line)|Out-Null
$global:LogStream.Flush()|Out-Null
}
return
}
if($Level -eq "ERROR") {
Write-Warning $Line
} else {
Write-Host $Line
}
$global:LogStream.WriteLine($Line)|Out-Null
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
# This function is responsible to serialize objects in order to communicate with the namedpipe
begin {
$type = [PSObject].Assembly.GetType('System.Management.Automation.Serializer')
$ctor = $type.GetConstructor('instance,nonpublic', $null, @([System.Xml.XmlWriter]), $null)
$sw = New-Object System.IO.StringWriter
$xw = New-Object System.Xml.XmlTextWriter $sw
$serializer = $ctor.Invoke($xw)
}
process {
try {
[void]$type.InvokeMember("Serialize", "InvokeMethod,NonPublic,Instance", $null, $serializer, [object[]]@($InputObject))
} catch {
if($global:debug) {
Write-Log -Level ERROR -Message "Could not serialize $($InputObject.GetType()): $_" -forceVerbose
}
}
}
end {
[void]$type.InvokeMember("Done", "InvokeMethod,NonPublic,Instance", $null, $serializer, @())
$sw.ToString()
$xw.Close()
$sw.Dispose()
}
}
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
# This function is responsible to deserialize objects in order to communicate with the namedpipe
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [PSObject].Assembly.GetType('System.Management.Automation.Deserializer')
$ctor = $type.GetConstructor('instance,nonpublic', $null, @([xml.xmlreader]), $null)
$sr = New-Object System.IO.StringReader $xmlString
$xr = New-Object System.Xml.XmlTextReader $sr
$deserializer = $ctor.Invoke($xr)
$done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance')
while (!$type.InvokeMember("Done", "InvokeMethod,NonPublic,Instance", $null, $deserializer, @()))
{
try {
$type.InvokeMember("Deserialize", "InvokeMethod,NonPublic,Instance", $null, $deserializer, @())
} catch {
if($global:debug) {
Write-Log -Level ERROR -Message "Could not deserialize ${string}: $_" -forceVerbose
}
}
}
$xr.Close()
$sr.Dispose()
}
}
Function Start-NamedPipeClient {
param(
[string]$pipeName
)
# This function is responsible to creates namedpipe client in order to communicate with the namedpipe server.
# START SCRIPTBLOCK
[ScriptBlock]$ListenerScript = {
param(
[Parameter(Mandatory=$true)]
[string]$pipeName,
[Parameter(Mandatory=$true)]
[System.Collections.Queue]$producer,
[Parameter(Mandatory=$true)]
[System.Collections.Queue]$consumer,
[System.Int32]$SleepMilisecondsTime
)
function Start-NamedPipeClient {
param(
[Parameter(Mandatory=$true)]
[string]$pipeName,
[System.Int32]$SleepMilisecondsTime
)
# This function is responsible to find if the namedpipe server is up, and interact with it.
while(!(Find-InArray -Content $pipeName -Array [System.IO.Directory]::GetFiles("\\.\\pipe\\"))) {
Sleep -Milliseconds $SleepMilisecondsTime
}
$npipeClient = new-object System.IO.Pipes.NamedPipeClientStream(".", $pipeName, [System.IO.Pipes.PipeDirection]::InOut,
[System.IO.Pipes.PipeOptions]::None,
[System.Security.Principal.TokenImpersonationLevel]::Impersonation)
$npipeClient.Connect()
$pipeReader = new-object System.IO.StreamReader($npipeClient)
$pipeWriter = new-object System.IO.StreamWriter($npipeClient)
return $npipeClient, $pipeReader, $pipeWriter
}
$npipeClient, $pipeReader, $pipeWriter = Start-NamedPipeClient -pipeName $pipeName -SleepMilisecondsTime $SleepMilisecondsTime
if(!$npipeClient) {
$consumer.Enqueue(@($false, "Namedpipe not exists!"))|Out-Null
return;
}
$consumer.Enqueue(@($true, ""))|Out-Null
while($npipeClient.IsConnected) { # Wait until the namedpipe is disconnected
if( $producer.Count -eq 0) {
Sleep -Milliseconds $SleepMilisecondsTime
continue
}
$req = $producer.Dequeue() # collect requests from producer queue and send them to the namedpipe.
$pipeWriter.WriteLine($req)
$pipeWriter.Flush()
$results = $pipeReader.ReadLine() # collect the results from the namedpipe and store it on the consumer queue
if($results) {
$consumer.Enqueue($results)|Out-Null
}
if($req['FunctionName'] -eq "exit") {
return
}
}
$npipeClient.Dispose() # Close namedpipe connection
}
# END SCRIPTBLOCK
$ps = [PowerShell]::Create() # Creates the namedpipe client under a runspace
$ps.AddScript($ListenerScript)|Out-Null
@($pipeName, $global:Producer, $global:Consumer,$global:SleepMilisecondsTime)|ForEach {
$ps.AddArgument($_)|Out-Null
}
return $ps, $ps.BeginInvoke()
}
function Start-NamedpipeListener {
param()
# This function is responsible to creates a namedpipe client and wait until the server allows our connection
$global:ps, $global:handle = Start-NamedPipeClient -pipeName $global:NamedPipe
Write-Log -Level VERBOSE -Message "Waiting for interaction between the client and the server via NamedPipe.."
while($global:Consumer.Count -eq 0) {
sleep -Milliseconds $global:SleepMilisecondsTime
}
$status, $response = $global:Consumer.Dequeue()
if(!$status) {
Write-Log -Level ERROR -Message $($response) -forceVerbose
}
return $status
}
function Close-NamedPipeClient {
param(
[Parameter(Mandatory = $true)]
$ps,
[Parameter(Mandatory = $true)]
$handle
)
# This function is responsible to request the namedpipe server to close, and then, it closes the namedpipe client
$global:Producer.Enqueue((ConvertTo-CliXml -InputObject @{FunctionName="exit"}))|Out-Null
while(!$handle.IsCompleted) {
Sleep -Milliseconds $global:SleepMilisecondsTime
}
$ps.Runspace.CloseAsync()
}
function Invoke-NamedpipeMission {
param(
[Parameter(Mandatory=$true)]
[system.object]$MissionInfo
)
# This function is responsible to serialize and send missions to the namedpipe server, and then, collects the results
$global:Producer.Enqueue((ConvertTo-CliXml -InputObject $MissionInfo))|Out-Null
while($global:Consumer.Count -eq 0) {
sleep -Milliseconds $global:SleepMilisecondsTime
}
while($global:Consumer.Count -ne 0) {
$res = $global:Consumer.Dequeue()
$res = ConvertFrom-CliXml -InputObject $res
if(!$res.IsSuccess -and $res.Result) {
Write-Log -Level ERROR -Message "$($res.Result) (From NamedPipe)" -forceVerbose
}
return $res
}
}
function Skip-LastItem {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Array])]
param(
[System.Array]$Array
)
# This function is responsible to skip the last item in array (compatible with Powershell v2)
if($Array.Count -eq 1) {
return @();
}
return $Array[0..($Array.Count-2)]
}
function Get-GetHostByName {
[OutputType([string])]
param(
[Parameter(Mandatory=$true)]
[string]$Hostname
)
# This function is responsible to resolve ip address of hostname
if($Hostname -eq $env:COMPUTERNAME) {
return "127.0.0.1"
}
return [System.Net.Dns]::GetHostByName($Hostname).AddressList[0].IPAddressToString
}
function Get-GetHostByAddress {
[OutputType([string])]
param(
[Parameter(Mandatory=$true)]
[string]$RemoteIP
)
# This function is responsible to response hostname of ipaddress
try {
return [System.Net.Dns]::GetHostByAddress($RemoteIP).Hostname
} catch {
Write-Log -Level ERROR -Message $_ -forceVerbose
return ""
}
}
function Find-InArray {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Boolean])]
param(
$Content,
[system.array]$Array
)
# This function is responsible to find string in array (compatible with Powershell v2)
foreach($data in $Array) {
if($data -eq $Content) {
return $true
}
}
return $false
}
function Get-MachineIPAddresses {
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()|foreach {
$_.GetIPProperties()|Foreach {
%{ (($_.UnicastAddresses).Address).IPAddressToString }
}
}
}
Function Enum-HostList {
param(
[string]$HostList
)
# This function is responsible to collect hostlist (seperated by comma), detect if the host is ipaddress/CIDR range or hostname, and resolve them.
$MachineIPAddressList = Get-MachineIPAddresses
foreach($HostItem in $HostList.Split(",")) {
$HostItem = $HostItem.Trim()
if(!($HostItem -match $global:IPRegex -or $HostItem.Contains("/"))) {
try {
$IPAddress = Get-GetHostByName -Hostname $HostItem
} catch {
Write-Log -Level ERROR -Message $_
continue
}
if(Find-InArray -Content $IPAddress -Array $MachineIPAddressList) {
ForEach-Object { "127.0.0.1"}
continue
}
ForEach-Object{$IPAddress}
continue
}
if(!($HostItem.Contains("/"))) {
ForEach-Object{$HostItem}
continue
}
$NetworkAddress = ($HostItem.split("/"))[0]
[int]$NetworkLength = ($HostItem.split("/"))[1]
$IPLength = 32-$NetworkLength
$NetworkIP = ([System.Net.IPAddress]$NetworkAddress).GetAddressBytes()
[Array]::Reverse($NetworkIP)
$LongIP = ([System.Net.IPAddress]($NetworkIP)).Address
For ($IPGap=0; $IPGap -lt (([System.Math]::Pow(2, $IPLength))); $IPGap++) {
$IPAddress = ([System.Net.IPAddress]($LongIP+$IPGap)).GetAddressBytes()
[Array]::Reverse($IPAddress)
$IPAddress = ([System.Net.IPAddress]($IPAddress)).IPAddressToString
if(Find-InArray -Content $IPAddress -Array $MachineIPAddressList) {
ForEach-Object{"127.0.0.1"}
continue
}
ForEach-Object{$IPAddress}
}
}
}
function Get-DomainNameFromRemoteRegistryHKLM {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([string])]
param()
# Resolve domain name from using registry
if($global:ChoosenHive -eq "HKLM") {
try {
return (Read-RegString -Key "System\CurrentControlSet\Services\Tcpip\Parameters" -Value "Domain").ToLower().Split(".")[0]
} catch {
Write-Log -Level ERROR -Message $_ -forceVerbose
return ""
}
}
return ""
}
function Get-DomainNameFromRemoteRegistryHKCU {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([string])]
param()
# Resolve domain name from using registry
if($global:ChoosenHive -eq "HKCU") {
try {
return (Read-RegString -Key "Volatile Environment" -Value "USERDOMAIN").ToLower()
} catch {
Write-Log -Level ERROR -Message $_ -forceVerbose
return ""
}
}
return ""
}
function Get-DomainNameFromRemoteNetBIOSPacket {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP
)
if($RemoteIP -eq "127.0.0.1") {
return ""
}
try {
$HostName = Get-GetHostByAddress -RemoteIP $RemoteIP
$udpobject = new-Object system.Net.Sockets.Udpclient
$udpobject.Connect($RemoteIP,137)
$udpobject.Client.ReceiveTimeout = 2500
[byte[]]$Bytes = @(0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21, 0x00, 0x0)
[void]$udpobject.Send($Bytes,$Bytes.length)
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
$udpobject.Close()
$TotalResults = [System.BitConverter]::ToString($receivebytes[56])
$results = $receivebytes[57..$receivebytes.Count]
for($i = 0; $i -lt $TotalResults; $i++) {
$flatBit = [System.BitConverter]::ToString($results[((18 * $i) + 15)])
if($flatBit -ne "00") {
continue
}
$NetBIOSname = ([System.Text.Encoding]::ASCII.GetString($results[(18 * $i)..((18 *$i) + 14)])).Trim().ToLower()
if($NetBIOSname -eq $HostName.Split(".")[0]) {
continue
}
return $NetBIOSname
}
} catch {
Write-Log -Level ERROR -Message $_
return ""
}
}
function Get-DomainNameFromRemoteNetBIOS {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP
)
# This function is responsible to resolve domain name via remote NetBIOS over TCP (like nbtstat)
$res = Invoke-NamedpipeMission -MissionInfo @{FunctionName="Get-DomainNameFromRemoteNetBIOS"; Arguments=@{RemoteIP=$RemoteIP}}
if(!$res.IsSuccess) {
return ""
}
return $res.Result
}
function Get-DomainNameFromRemoteMachine {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP
)
<#
This function is responsible to resolve the domain name from the remote machine using DomainNameFromRemoteNetBIOSPacket function,
if it failse, it will try to resolve it using Get-DomainNameFromRemoteNetBIOS function.
If it fails, it will try to resolve it using DomainNameFromRemoteRegistryHKLM function
if it fails, it will try to resole it using DomainNameFromRemoteRegistryHKCU.
#>
if(!$global:RemoteDomain) {
$DomainName = Get-DomainNameFromRemoteNetBIOSPacket -RemoteIP $RemoteIP
if($DomainName) {
Write-Log -Level VERBOSE -Message "Remote Domain: $($DomainName) | Technique: NetBIOS Packet"
$global:RemoteDomain = $DomainName
return $DomainName
}
$DomainName = Get-DomainNameFromRemoteNetBIOS -RemoteIP $RemoteIP
if($DomainName) {
Write-Log -Level VERBOSE -Message "Remote Domain: $($DomainName) | Technique: NetBIOS NetAPI"
$global:RemoteDomain = $DomainName
return $DomainName
}
$DomainName = Get-DomainNameFromRemoteRegistryHKLM
if($DomainName) {
Write-Log -Level VERBOSE -Message "Remote Domain: $($DomainName) | Technique: Registry (HKLM)"
$global:RemoteDomain = $DomainName
return $DomainName
}
$Hive = $global:ChoosenHive
Test-RegistryConnection -RemoteIP $RemoteIP -Hive HKCU|Out-Null
$DomainName = Get-DomainNameFromRemoteRegistryHKCU
Test-RegistryConnection -RemoteIP $RemoteIP -Hive $Hive|Out-Null
if($DomainName) {
Write-Log -Level VERBOSE -Message "Remote Domain: $($DomainName) | Technique: Registry (HKCU)"
$global:RemoteDomain = $DomainName
return $DomainName
}
}
return $global:RemoteDomain
}
function is-DomainJoinedUserSession {
param(
[string]$RemoteIP
)
# This function is responsible to check if the attacker machine is domain-joined user (or attack the loopback :D)
return ((is-LoopBack -RemoteIP $RemoteIP) -or $env:userdomain.ToLower() -eq (Get-DomainNameFromRemoteMachine -RemoteIP $RemoteIP))
}
function Get-userSID {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Array])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP,
[Parameter(Mandatory = $true)]
[string]$Username # Gets username without domain-name
)
# This function is responsible to resolve the user SID using WindowsIdentity feature, if it fails, it will try to produce it using ADSI protocool
if(Find-InArray -Content $Username -Array $global:CachedData['UserSIDList'].Keys) {
return $global:CachedData['UserSIDList'][$Username]
}
# If the user that needs to be analyzed is in the same domain environment, try to resolve the groups using ASDI protocol
$SID = Get-UserSIDUsingADSI -RemoteIP $RemoteIP -Username $Username
if($SID) {
Write-Log -Level VERBOSE -Message "$($Username) resolved user SID using ADSI"
$global:CachedData['UserSIDList'][$Username] = $SID
return $SID
}
if(is-DomainJoinedUserSession -RemoteIP $RemoteIP) {
try {
if($Username -eq $env:username) {
$SID = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value
}else {
$SID = ([System.Security.Principal.WindowsIdentity]($Username)).User.Value
}
Write-Log -Level VERBOSE -Message "$($Username) Resolved identity SID using WindowsIdentity"
$global:CachedData['UserSIDList'][$Username] = $SID
return $SID
} catch {
Write-Log -Level ERROR -Message $_ -forceVerbose
}
}
# If fails, or the user is not domained-joined, try to resolve groups using the windows-identity feature.
Write-Log -Level ERROR -Message "Can't resolve user SID"
return $false
}
function Get-GroupSID {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Array])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP,
[Parameter(Mandatory = $true)]
[string]$GroupName
)
# This function is responsible to resolve the group SID using NTAccount feature, if it fails, it will try to produce it using ADSI protocool
if(Find-InArray -Content $GroupName -Array $global:CachedData['GroupSIDList'].Keys) {
return $global:CachedData['GroupSIDList'][$GroupName]
}
# If fails, or the user is not domained-joined, try to resolve groups using ASDI protocol.
$SID = Get-GroupSIDUsingADSI -RemoteIP $RemoteIP -GroupName $GroupName
if($SID) {
Write-Log -Level VERBOSE -Message "${GroupName} Group Resolved SID using ADSI"
$global:CachedData['GroupSIDList'][$GroupName] = $SID
return $SID
}
try {
$SID = ([System.Security.Principal.NTAccount]($GroupName)).Translate([security.principal.securityidentifier]).Value
Write-Log -Level VERBOSE -Message "${GroupName} Group Resolved SID using NTAccount"
$global:CachedData['GroupSIDList'][$GroupName] = $SID
return $SID
} catch {
Write-Log -Level ERROR -Message $_
}
Write-Log -Level ERROR -Message "Can't resolve group SID"
return $false
}
function Get-UserGroupsUsingWindowsIdentity {
param(
[Parameter(Mandatory = $true)]
[System.Security.Principal.WindowsIdentity]$Token
)
# This function is responsible to resolve SID groups of user (include his user SID)
% {@{GroupName=$Token.Name.Split("\")[-1]; SID=$Token.User.Value}}
Foreach($sid in $Token.Groups) {
try {
$groupName = ([System.Security.Principal.SecurityIdentifier]$sid).Translate([System.Security.Principal.NTAccount]).ToString()
# Remove all uppercase groups(INTERACTIVE, SELF, etc.)
if($groupName.Contains("NT AUTHORITY\") -or ($groupName -ceq $groupName.ToUpper())) {
continue
}
$global:CachedData['GroupSIDList'][$GroupName] = $sid.Value
%{ $sid.Value }
} catch {
continue
}
}
}
function Get-UserToken {
param(
[Parameter(Mandatory = $true)]
[string]$Username
)
try {
return [System.Security.Principal.WindowsIdentity]($Username)
} catch {
Write-Log -Level ERROR -Message $_ -forceVerbose
return $false
}
}
function Check-Username {
[OutputType([string])]
param(
[string]$Username
)
return (Iif -Condition $Username -Right $Username.Replace("/", "\") -Wrong "$($env:USERDOMAIN)\$($env:USERNAME)")
}
function Get-UserGroup {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Array])]
param(
[Parameter(Mandatory = $true)]
[string]$RemoteIP,
[Parameter(Mandatory = $true)]
[string]$Username # Gets username without domain-name
)
%{ (Get-GroupSID -RemoteIP $RemoteIP -GroupName "Everyone") }
# Try to resolve groups using ASDI protocol.
$res = Get-UserGroupsUsingADSI -RemoteIP $RemoteIP -Username $Username
if($res) {
Write-Log -Level VERBOSE -Message "Resolved user groups using ADSI (Identity: $($Username))"
return $res
}
# Try to resolve groups using WindowsIdentity.
if(is-DomainJoinedUserSession -RemoteIP $RemoteIP) {
$Token = Get-UserToken -Username $Username
if($Token) {
Get-UserGroupsUsingWindowsIdentity -Token $Token
Write-Log -Level VERBOSE -Message "Resolved user groups using WindowsIdentity (Identity: $($Username))"
return
}
if($Username -eq $env:USERNAME) {
# Try to resolve groups using WindowsIdentity using current session.
Get-UserGroupsUsingWindowsIdentity -Token ([System.Security.Principal.WindowsIdentity]::GetCurrent())
Write-Log -Level VERBOSE -Message "Resolved user groups using WindowsIdentity (Identity: $($Username) (Current session groups))"
return
}
Write-Log -Level VERBOSE -Message "Can't resolve user groups, trying to guess groups."
}
# If fails, try to guess the groups.
@((Get-userSID -RemoteIP $RemoteIP -Username $Username), (Get-GroupSID -RemoteIP $RemoteIP -GroupName "Users"))|Foreach {
% { $_ }
}
if(is-DomainJoinedUserSession -RemoteIP $RemoteIP) {
%{ (Get-GroupSID -RemoteIP $RemoteIP -GroupName "Domain users") }
}
}
function IIf {
param
(
$Condition,
[Parameter(Mandatory = $true)]
$Right,
[Parameter(Mandatory = $true)]
$Wrong
)
# If/else oneliner, it uses when we want to simplify basic operations.
if ($Condition) {
return $Right
}
return $Wrong
}
function Start-RunAsSession {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True)]
[String]$Domain,
[Parameter(Mandatory = $True)]
[String]$Username,
[String]$Password,
[Parameter(Mandatory = $True)]
[string]$Filename,
[string]$Arguments,
[switch]$NetOnly
)
# This function is responsible to create a process using provided credentials/current session for the namedpipe process.
if(!$Password) {
$WindowStyle = Iif -Condition $global:debug -Right "Normal" -Wrong "Hidden"
Start-Process -FilePath $Filename -ArgumentList @($Arguments) -WindowStyle $WindowStyle
return $true
}
Add-Type -TypeDefinition @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
public static class Advapi32
{
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
public static extern bool CreateProcessWithLogonW(
String userName,
String domain,
String password,
int logonFlags,
String applicationName,
String commandLine,
int creationFlags,
int environment,
String currentDirectory,
ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION processInformation);
}
public static class Kernel32
{
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
}
'@
# StartupInfo Struct
$StartupInfo = New-Object STARTUPINFO
$StartupInfo.dwFlags = 0x00000001
$StartupInfo.wShowWindow = Iif -Condition $global:debug -Right 0x0001 -Wrong 0x0000 # 0x0000 - Hide window, 0x0001 - Show window
$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo)
# ProcessInfo Struct
$ProcessInfo = New-Object PROCESS_INFORMATION
# CreateProcessWithLogonW --> lpCurrentDirectory
$GetCurrentPath = (Get-Item -Path ".\").FullName
$CallResult = [Advapi32]::CreateProcessWithLogonW(
$Username.Split("\")[-1], $Domain, $Password, (Iif -Condition $NetOnly -Right 0x2 -Wrong 0x1),
$Filename, $Arguments, 0x04000000, $null, $GetCurrentPath,
[ref]$StartupInfo, [ref]$ProcessInfo)
if (!$CallResult) {
Write-Log -Level ERROR -Message $((New-Object System.ComponentModel.Win32Exception([int][Kernel32]::GetLastError())).Message).ToString()
return $false
}
return $true
}
function Start-NamedPipe-Server {
[CmdletBinding(SupportsShouldProcess=$true)]
[OutputType([System.Array])]
param(
[string]$Username,
[string]$Password
)
# This function is responsible to create a new process using Start-RunAsSession function, and inject the server payload
$ServerContent = @'
$global:reg = ""
$global:RemoteIP = ""
$global:ChoosenHive = ""
$global:StdRegProvHive = ""
$global:RegAuthenticationMethod = ""
$global:COMObject = $null
$global:COMSnapshots = @{}
$global:COMTimeout = [COMTIMEOUT] # Max COMObject intraction timeout
$global:debug = [DEBUG]
$global:SleepMilisecondsTime = [SLEEPTIME]
$global:RunSpaceClosedList = New-Object System.Collections.ArrayList
# Add NetAPI libraries
Add-Type -MemberDefinition @"
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint NetApiBufferFree(IntPtr Buffer);
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int NetGetJoinInformation(
string server,
out IntPtr NameBuffer,
out int BufferType);
"@ -Namespace Win32Api -Name NetApi32
# NamedPipe functions
function Start-NamedPipeServer {
[OutputType([System.Array])]
param(
[Parameter(Mandatory=$true)]
[string]$pipeName
)
# This function is responsible to start a NamedPipe server
$PipeSecurity = new-object System.IO.Pipes.PipeSecurity
$AccessRule = New-Object System.IO.Pipes.PipeAccessRule( "Everyone", "FullControl", "Allow" )
$PipeSecurity.AddAccessRule($AccessRule)
$pipeDir = [System.IO.Pipes.PipeDirection]::InOut
$pipeMsg = [System.IO.Pipes.PipeTransmissionMode]::Message
$pipeOpti = [System.IO.Pipes.PipeOptions]::Asynchronous
$npipeServer = New-Object system.IO.Pipes.NamedPipeServerStream($pipeName, $pipeDir, 100, $pipeMsg, $pipeOpti, 32760, 32760, $PipeSecurity )
$npipeServer.WaitForConnection();
$pipeReader = new-object System.IO.StreamReader($npipeServer)
$pipeWriter = new-object System.IO.StreamWriter($npipeServer)
return $npipeServer, $pipeReader, $pipeWriter
}
function Remove-ClosedRunSpaces {
param()
# This function is responsible to remove all closed runspaces - compatible with powershell v2
$idx = 0
$rsList = {$($global:RunSpaceClosedList|?{$_})}.Invoke()
foreach($ps in $rsList) {
if($ps.RunspaceStateInfo.State -ne "Closed") {
$idx += 1
continue
}
$ps.Dispose()
$global:RunSpaceClosedList.RemoveAt($idx)|Out-Null
}
}
function Start-NamedPipeManager {
param(
[string]$pipeName
)
# This function is responsible to launch and manage the pipe communication.
while($true) {
$npipeServer, $pipeReader, $pipeWriter = Start-NamedPipeServer -pipeName $pipeName
while($true) {
try {
$res = $pipeReader.ReadLine()
if(!$res) {
$npipeServer.Dispose()
break
}
if($global:debug) {
Write-Host $res
}
$res = ConvertFrom-CliXml -InputObject $res
$FunctionName = $res['FunctionName']