forked from get-get-get-get/PowerProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowerProxy.ps1
More file actions
1720 lines (1363 loc) · 51.4 KB
/
Copy pathPowerProxy.ps1
File metadata and controls
1720 lines (1363 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
Author: @GetGetGetGet (github.com/get-get-get-get)
License: GNU GPLv3
#>
##########
# Servers
#####
function Start-ReverseSocksProxy {
<#
.SYNOPSIS
Connects to remote machine and acts as Socks server to tunnel traffic out.
.DESCRIPTION
Connects back to remote handler, then starts job tunneling connection out as proxy.
.EXAMPLE
# Act as proxy for remote machine listening at 172.1.1.20, port 2200
Invoke-ReverseSocksProxy -RemoteHost 172.1.1.20 -Port 2200
# Require authentication
$Password = ConvertTo-SecureString -AsPlaintext -Force "Pa$$w0rd123"
$Cred = New-Object System.Management.Automation.PSCredential ("ProxyUser", $Password)
.EXAMPLE
# Verify SSL cert of remote machine, and use SystemProxy
Invoke-ReverseSocksProxy -RemoteHost 172.1.1.20 -SystemProxy -FingerPrint 93061FDB30D69A435ACF96430744C5CC5473D44E -Verbose
.PARAMETER RemoteHost
IP address of remote handler.
.PARAMETER RemotePort
Port on handler to connect to. Default = 443
.PARAMETER Certificate
Validate remote certificate matches given fingerprint.
.PARAMETER MaximumRetries
Maximum consecutive attempts to connect to handler before failure.
.PARAMETER WaitBeforeRetry
Seconds to wait after failed connection before trying again.
.PARAMETER Connections
Number of connections to maintain with remote host. Default: 10
.PARAMETER NoEncryption
Connect to remote host without TLS
.PARAMETER Version
Socks version
.PARAMETER SystemProxy
Tunnel via default system proxy.
.PARAMETER Credential
PSCredential. Clients will require USERPASS authentication, and version is restricted to Socks5
#>
[Alias("Start-ReverseProxy", "Invoke-ReverseProxy", "Invoke-ReverseSocksProxy")]
# CMDletBinding should add support for Write-Verbose, among other things
[CMDletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipelineByPropertyName = $true)]
[Alias('Rhost', 'Address', 'IP', 'HandlerAddress')]
[string]
$RemoteHost,
[Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)]
[Alias('Rport', 'Port')]
[ValidateScript( { $_ -le 65535 })]
[int]
$RemotePort = 443,
[Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
[Alias('Validate', 'Fingerprint', 'Cert')]
[string]
$Certificate = "",
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('UseSystemProxy')]
[switch]
$SystemProxy = $False,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Cleartext', 'NoSSL', 'NoTLS')]
[switch]
$NoEncryption = $False,
# TODO: accept array of credentials
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('USERPASS', 'SocksCredential')]
[pscredential]
$Credential,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Retries', 'MaxRetries', 'MaxRetry')]
[int]
$MaximumRetries = 10,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('MaxConnections', 'MaximumConnections', 'Threads')]
[int]
$Connections = 10,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Wait')]
[int]
$WaitBeforeRetry = 3,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet(4, 5)]
[Alias('SocksVersion')]
[int[]]
$Version = @(4, 5)
)
if ($Credential) {
Write-Warning "[!] Authentication is untested and should be considered insecure!"
if ($Version -contains 4) {
Write-Host "[!] Only Socks5 supports authentication! Restricting version to Socks5"
$Version = @(5)
}
# Does this ampersand look like a lock?
Write-Host "Securing proxy with Username/Password authentication"
}
<#
1. Create synchonized objects for tracking certain states (e.g. connections, failures)
1.5 Create ScriptBlock calling Invoke-ReverseProxyWorker with args being subset of current
2. Create thread/runspace pool, where one thread is a single connection to remote proxy handler
3. Spin up threads via some worker function, like Invoke-ReverseProxyWorker
4. Invoke-ReverseProxyWorker threads should report back on certain states via the synchronized objects (step 1)
5. Invoke-ReverseProxyWorker call Start-SocksProxyConnection if they get wake sequence from remote
6. This thread is master, monitors threads via synchronized objects, acts based on condition
#>
###### 1.5 Create Scriptblock (Need to implement version arg better, and in future add auth info)
# Args to pass to worker function
$WorkerArgs = new-object psobject -Property @{
RemoteHost = $RemoteHost
RemotePort = $RemotePort
Certificate = $Certificate
SystemProxy = $SystemProxy
NoEncryption = $NoEncryption
MaximumRetries = $MaximumRetries
WaitBeforeRetry = $WaitBeforeRetry
Credential = $Credential
Version = $Version
Verbose = ($VerbosePreference -eq "CONTINUE")
}
# will this work?
$ScriptBlock = {
$WorkerArgs | Invoke-ReverseProxyWorker -Verbose:$WorkerArgs.Verbose
}
##### 2. Create runspace pool
# InitialSessionState for eventual runspacepool
$InitialSessionState = [initialsessionstate]::CreateDefault()
### stolen from stackoverflow
# https://stackoverflow.com/questions/51818599/how-to-call-outside-defined-function-in-runspace-scriptblock
# Add all dot-sourced functions to ISS
# includes functions from imported modules, but NOT iex ones...
Get-ChildItem function:\ | Where-Object Source -like "" | ForEach-Object {
$FunctionDefinition = Get-Content "Function:\$($_.Name)"
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $_.Name, $functionDefinition
$InitialSessionState.Commands.Add($SessionStateFunction)
}
# Add variables to ISS ?
# https://stackoverflow.com/questions/38102068/sessionstateproxy-variable-with-runspace-pools
$WorkerVariable = New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'WorkerArgs', $WorkerArgs, $null
$InitialSessionState.Variables.Add($WorkerVariable)
# Create runspacepool
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $Connections, $InitialSessionState, $Host)
$RunspacePool.Open()
###### 3. Start threads, add to workers array
# Create array to track workers. Set length to avoid creating a new one w/ '+='
$Workers = @(1..$Connections)
$WorkersAsync = @(1..$Connections)
# Start workers
for ($i = 0; $i -lt $Connections; $i++) {
# Instantiate
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
$PowerShell.AddScript($ScriptBlock) | Out-Null
# Invoke and store as psobject
$Worker = new-object psobject -Property @{
Powershell = $PowerShell
AsyncResult = $PowerShell.BeginInvoke()
}
# Also store AsyncResult in its own array for easy status check
$WorkersAsync[$i] = $Worker.AsyncResult
# Add to array
$Workers[$i] = $Worker
}
Write-Host "Opening $Connections connections to handler at $RemoteHost"
##### 6. Monitor threads
# https://blogs.technet.microsoft.com/dsheehan/2018/10/27/powershell-taking-control-over-ctrl-c/
# Change the default behavior of CTRL-C so that the script can intercept and use it versus just terminating the script.
# [Console]::TreatControlCAsInput is invalid if not TTY
try {
$OldControlCAsInput = [Console]::TreatControlCAsInput
$TerminalIsTTY = $True
}
catch {
$TerminalIsTTY = $False
}
try {
if ($TerminalIsTTY) {
[Console]::TreatControlCAsInput = $True
Start-Sleep -Seconds 1 # Helps flush buffer
$Host.UI.RawUI.FlushInputBuffer()
}
# TODO: implement failure monitoring, map connections to track status
while ($WorkersAsync.IsCompleted -contains $false) {
if ($TerminalIsTTY) {
if ($Host.UI.RawUI.KeyAvailable -and ($Key = $Host.UI.RawUI.ReadKey("AllowCtrlC,NoEcho,IncludeKeyUp"))) {
if ([Int]$Key.Character -eq 3) {
Write-Host ""
Write-Warning "CTRL-C detected - closing connections and exiting"
foreach ($Worker in $Workers) {
$Worker.Powershell.dispose()
}
}
# Flush the key buffer again for the next loop.
$Host.UI.RawUI.FlushInputBuffer()
}
}
else {
Start-Sleep -Seconds 1
}
}
}
finally {
if ($TerminalIsTTY) {
[Console]::TreatControlCAsInput = $OldControlCAsInput
}
else {
Write-Host "[!] Closing connections and exiting"
foreach ($Worker in $Workers) {
$Worker.Powershell.dispose()
}
}
}
}
function Start-SocksProxy {
<#
.SYNOPSIS
Starts Socks proxy server
.DESCRIPTION
Binds to given address and listens for incoming connections to proxy forward
.EXAMPLE
# Run proxy server on 172.10.2.20, port 9050
Start-SocksProxy 172.10.2.20 -Port 9050
# Require authentication
$Password = ConvertTo-SecureString -AsPlaintext -Force "Pa$$w0rd123"
$Cred = New-Object System.Management.Automation.PSCredential ("ProxyUser", $Password)
Start-SocksProxy -Address 192.168.0.24 -Credential $Cred -Verbose
.PARAMETER Address
IP address to listen bind to.
.PARAMETER Port
TCP Port to listen on. Default: 1080
.PARAMETER Credential
PSCredential with Username and Password of valid users. Forces Socks5 as version
.PARAMETER Version
Socks version (4 or 5)
.PARAMETER Threads
Number of threads for handling connections. Default: 200
.PARAMETER Encryption
Use TLS to encrypt connections with clients. (not implemented)
#>
[Alias('Invoke-BindProxy', 'Start-BindProxy', 'Start-SocksProxyServer')]
# CMDletBinding should add support for Write-Verbose, among other things
[CMDletBinding()]
param (
[Parameter(Mandatory = $True, Position = 0, ValueFromPipelineByPropertyName = $true)]
[Alias('Address', 'IP', 'Host', 'Lhost', 'ListenAddress')]
[String]
$BindAddress,
[Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)]
[Alias('Port', 'Lport')]
[ValidateScript( { $_ -le 65535 })]
[Int]
$BindPort = 1080,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Connections', 'MaxThreads', "MaxConnections")]
[Int]
$Threads = 200,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('SSL', 'TLS')]
[switch]
$Encryption = $False,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('USERPASS', 'SocksCredential')]
[pscredential]
$Credential,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet(4, 5)]
[Alias('SocksVersion')]
[int[]]
$Version = @(4, 5)
)
if ($Credential) {
Write-Warning "[!] Authentication is untested and should be considered insecure!"
if ($Version -contains 4) {
Write-Host "[!] Only Socks5 supports authentication! Restricting version to Socks5"
$Version = @(5)
}
# Does this ampersand look like a lock?
Write-Host "Securing proxy with Username/Password authentication"
}
<#
1. Create runspacepool for spinning clients off into a different thread
2. Listen for connections, spin connections off into thread
3. Track threads and connections somehow
#>
# Args to pass to worker function
$WorkerArgs = new-object psobject -Property @{
Version = $Version
Credential = $Credential
Verbose = ($VerbosePreference -eq "CONTINUE")
}
# InitialSessionState for eventual runspacepool
$InitialSessionState = [initialsessionstate]::CreateDefault()
### stolen from stackoverflow
# https://stackoverflow.com/questions/51818599/how-to-call-outside-defined-function-in-runspace-scriptblock
# Add all dot-sourced functions to ISS
# includes functions from imported modules, but NOT iex ones...
Get-ChildItem function:\ | Where-Object Source -like "" | ForEach-Object {
$FunctionDefinition = Get-Content "Function:\$($_.Name)"
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $_.Name, $functionDefinition
$InitialSessionState.Commands.Add($SessionStateFunction)
}
# Add variables to ISS ?
# https://stackoverflow.com/questions/38102068/sessionstateproxy-variable-with-runspace-pools
$WorkerVariable = New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'WorkerArgs', $WorkerArgs, $null
$InitialSessionState.Variables.Add($WorkerVariable)
# Track threads
$Workers = @()
# Track connections received
$ConnectionCount = 0
try {
# TCP listener
$SocksListener = new-object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse($BindAddress), $BindPort)
$SocksListener.start()
Write-Host "Listening on $BindAddress`:$BindPort"
# Handle Ctrl-C
try {
$OldControlCAsInput = [Console]::TreatControlCAsInput
[Console]::TreatControlCAsInput = $True
$TerminalIsTTY = $True
Start-Sleep -Seconds 1 # Helps flush buffer
$Host.UI.RawUI.FlushInputBuffer()
}
catch {
$TerminalIsTTY = $False
}
# Listen and serve
while ($true) {
# Check for pending connections (structured to avoid blocking)
if ($SocksListener.Pending() -eq $True) {
# Accept incoming connection
$Client = $SocksListener.AcceptTcpClient()
$ClientStream = $Client.GetStream()
Write-Host "[*] New Connection from $($Client.Client.RemoteEndPoint)"
$ConnectionCount++
if ($Encryption) {
Write-Verbose "[!] ERROR: I didn't do encryption stuff yet"
raise "Encryption bullshit" # idk lol
}
####################
# workaround to add clientstream var to runspace
###########
# Add ClientStream var to InitialSessionState (Does this fuck up next time a client comes?)
$ClientStreamVariable = New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'ClientStream', $ClientStream, $null
$InitialSessionState.Variables.Add($ClientStreamVariable)
# Create Runspace using InitialSessionState
$Runspace = [runspacefactory]::CreateRunspace($Host, $InitialSessionState)
$Runspace.open()
# Add scriptblock
$ScriptBlock = {
$WorkerArgs | Start-SocksProxyConnection -Verbose:$WorkerArgs.Verbose -ClientStream $ClientStream
}
$PowerShell = [PowerShell]::Create()
$PowerShell.Runspace = $Runspace
$PowerShell.AddScript($ScriptBlock)
# Store worker
$Worker = New-Object psobject -Property @{
"PowerShell" = $PowerShell
"AsyncResult" = $PowerShell.BeginInvoke()
}
# Add worker to workers array
$Workers += $Worker
$ThreadCount++
#Write-Verbose "Threads remaining: $($RunSpacePool.GetAvailableRunspaces())"
}
# Check for ctrl-c
else {
if ($TerminalIsTTY) {
if ($Host.UI.RawUI.KeyAvailable -and ($Key = $Host.UI.RawUI.ReadKey("AllowCtrlC,NoEcho,IncludeKeyUp"))) {
if ([Int]$Key.Character -eq 3) {
Write-Host ""
Write-Warning "CTRL-C detected - closing connections and exiting"
Foreach ($Worker in $Workers) {
$Worker.PowerShell.Dispose()
}
[Console]::TreatControlCAsInput = $False
break
}
# Flush the key buffer again for the next loop.
$Host.UI.RawUI.FlushInputBuffer()
}
}
else {
Start-Sleep -Seconds 1
}
}
}
}
Catch {
Write-Warning "Error in SOCKS listener: $($_.Exception.Message)"
}
Finally {
# Reset Ctrl-C handling to normal
if ($TerminalIsTTY) {
[Console]::TreatControlCAsInput = $OldControlCAsInput
}
Write-Verbose "Server closing..."
Write-Host "Total connections received: $ConnectionCount"
foreach ($Worker in $Workers) {
$Worker.PowerShell.dispose()
}
# Close connections and jobs before exiting
if ($null -ne $SocksListener) {
$SocksListener.Stop()
}
Write-Host "[-] Server closed"
}
}
##########
# MISC
#####
function Invoke-ReverseProxyWorker {
<#
.SYNOPSIS
Called by Start-ReverseSocksProxy. Connects to remote machine and acts as Socks server to tunnel traffic out.
#>
[CMDletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipelineByPropertyName = $true)]
[Alias('Rhost', 'Address', 'IP', 'HandlerAddress')]
[string]
$RemoteHost,
[Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)]
[Alias('Rport', 'Port')]
[ValidateScript( { $_ -le 65535 })]
[int]
$RemotePort = 443,
[Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
[Alias('Validate', 'Fingerprint', 'Cert')]
[string]
$Certificate = "",
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Cleartext', 'NoSSL', 'NoTLS')]
[switch]
$NoEncryption = $False,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Alias('USERPASS', 'SocksCredential')]
[pscredential]
$Credential,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Retries', 'MaxRetries', 'MaxRetry')]
[int]
$MaximumRetries = 20,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('UseSystemProxy')]
[switch]
$SystemProxy = $False,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('Wait')]
[int]
$WaitBeforeRetry = 3,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet(4, 5)]
[Alias('SocksVersion')]
[int[]]
$Version = @(4, 5)
)
# TODO: something better.
$ProxyArgs = new-object psobject -Property @{
RemoteHost = $RemoteHost
RemotePort = $RemotePort
Certificate = $Certificate
SystemProxy = $SystemProxy
WaitBeforeRetry = $WaitBeforeRetry
Credential = $Credential
Version = $Version
Verbose = ($VerbosePreference -eq "CONTINUE")
}
<#
1. Map message from remote to appropriate reply and action
a. 'WAKE' --> reply 'WOKE' --> Start-ProxyConnection
b. 'KILL --> reply 'DEAD' --> signal master thread to shut shit down
2. Start while loop of connecting to remote host
a. Exceptions/failures should report to master via synchronized object (not implemented)
b. Successful connections should be tracked via synchronized object
3. Within (2), a while loop listening for messages from remote
a. If messaage launches a proxy connection, that should be reported to master
#>
# 1. Define messages, map to reply and action
$WakeMessage = @{
Message = "WAKE"
BYTES = Convert-StringToBytes "WAKE"
Reply = Convert-StringToBytes "WOKE"
}
$KillMessage = @{
Message = "KILL"
BYTES = Convert-StringToBytes "KILL"
Reply = Convert-StringToBytes "DEAD"
}
$Messages = $WakeMessage, $KillMessage
$ConnectFailures = 0
# 2. Connection loop
while ($true) {
# SNIPPET: connection flow
try {
# Try to connect
try {
# Handle $SystemProxy option
if ($SystemProxy -eq $false) {
$Client = New-Object System.Net.Sockets.TcpClient($RemoteHost, $RemotePort)
$ClientStream_Clear = $Client.GetStream()
}
else {
$ret = Get-SystemProxy -RemoteHost $RemoteHost -RemotePort $RemotePort
$Client = $ret[0]
$ClientStream_Clear = $ret[1]
}
# Reset counter
$ConnectFailures = 0
}
catch {
if ($ConnectFailures -eq 0) {
Write-Warning "[!] Connection to remote host fucking failed! :)"
}
$ConnectFailures++
if ($ConnectFailures -ge $MaximumRetries) {
Write-Warning "[!] Connection failures maxed out! Exiting"
return
}
Write-Verbose "$($MaximumRetries - $ConnectFailures) connection attempts remain"
Start-Sleep $WaitBeforeRetry
continue
}
# SSL - handle certificate verification options
if ($NoEncryption) {
$ClientStream = $ClientStream_Clear
Write-Verbose "[+] Connected to $RemoteHost`:$RemotePort"
}
else {
if ($Certificate -eq '') {
$ClientStream = New-Object System.Net.Security.SslStream($ClientStream_Clear, $false, ( { $true } -as [Net.Security.RemoteCertificateValidationCallback]));
}
else {
# Checks if cert hash string matches hash given in $Validate param
$ClientStream = New-Object System.Net.Security.SslStream($ClientStream_Clear, $false, ( { return $args[1].GetCertHashString() -eq $Certificate } -as [Net.Security.RemoteCertificateValidationCallback]));
}
# SSL - do handshake (?)
$ClientStream.AuthenticateAsClient($RemoteHost)
if ($ClientStream.IsAuthenticated) {
Write-Verbose "[+] Connected to $RemoteHost`:$RemotePort"
}
else {
Write-Error "[!] Encryption failed!"
}
}
# 3. Listen for message loop
# Read a byte at a time, only listen for start of message
[byte[]] $Alert = ( $messages | ForEach-Object { $_.bytes[0] } )
# Buffer to read into
$Buffer = New-Object System.Byte[] 4
# Set timeout
$OldTimeout = $ClientStream.ReadTimeout
$ClientStream.ReadTimeout = 500
while ($true) {
# Question: if you read from a socket that's "empty", how is that represented
# Also, what if message is split between reads??? e.g. "00WA" "KE00"
# Read a byte at a time
try {
$ClientStream.Read($Buffer, 0, 1)
}
catch [System.IO.IOException] {
continue
}
# If byte matches start of a message, test if it's a message
if ($Buffer[0] -in $Alert) {
$ClientStream.ReadTimeout = $OldTimeout
# Read rest of message
$ClientStream.Read($Buffer, 1, 3)
# Check if matches any known message
foreach ($key in $messages) {
# If it's a message, send the reply and take the action
if ((Compare-Object $key.bytes $buffer -SyncWindow 0).length -eq 0) {
$Message = $key.Message
$Buffer = $key.reply
$ClientStream.Write($Buffer, 0, $Buffer.length)
$ClientStream.Flush()
Write-Verbose "Received message from handler: '$($Message)'"
}
}
# Do the action then
if ($Message) {
if ($Message -eq "WAKE") {
$ProxyArgs | Start-SocksProxyConnection $ClientStream -Verbose:$ProxyArgs.Verbose
break
}
elseif ($Message -eq "KILL") {
return
}
}
}
}
# Connection complete
$Clientstream.Close()
$Client.Close()
Write-Verbose "[-] Job complete, connection to $RemoteHost closed"
}
catch {
Write-Verbose "[!] ERROR in ReverseProxyWorker: $($_.Exception.Message)"
#throw $_
# TODO: report to master thread
# TODO: handle exception, probably just pass
}
finally {
# Note: figure out the flow/order of shutting this down
if ($Client.connected -eq $True) {
Write-Verbose "[-] Closed connection to $RemoteHost"
}
$ClientStream.close()
$Client.Close()
}
}
}
function Connect-TcpStreams {
<#
.SYNOPSIS
Forward TCP traffic after SOCKS connection started
#>
[Alias('Forward-TcpStreams')]
[CMDletBinding()]
param (
# Client TCP stream
[Parameter(Mandatory = $True, Position = 0, ValueFromPipelineByPropertyName = $true)]
$ClientStream,
# TODO: figure out type to list here, or just don't put type.
[Parameter(Mandatory = $True, Position = 1, ValueFromPipelineByPropertyName = $true)]
$TargetStream
)
# Client/Destinations Streams are asynchronously copied
$AsyncCopyResult_A = $ClientStream.CopyToAsync($TargetStream)
$AsyncCopyResult_B = $TargetStream.CopyToAsync($ClientStream)
# Wait for each copy to complete
# TODO: fix issue where this never finishes, even though client closes connection
# Issue is that the Python handler isn't checking connection status
$AsyncCopyResult_A.AsyncWaitHandle.WaitOne()
$AsyncCopyResult_B.AsyncWaitHandle.WaitOne()
Write-Host "[x] Tunneling complete"
return
}
##########
# SOCKS (generic/agnostic)
#####
function Start-SocksProxyConnection {
<#
.SYNOPSIS
Handles SOCKS requests
.DESCRIPTION
Starts SOCKS process. Called by proxy servers upon receiving connection
.PARAMETER ClientStream
NetStream/SSLStream object representing client connection
.PARAMETER Version
4 or 5. Default: both
.PARAMETER Credential
PSCredential. Clients will require USERPASS authentication, and version is restricted to Socks5
.PARAMETER AcceptedMethod
Socks5 Method to accept in negotiation
#>
[CMDletBinding()]
param (
# Client TCP stream
[Parameter(Mandatory = $True, Position = 0, ValueFromPipelineByPropertyName = $true)]
$ClientStream,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet(4, 5)]
[Alias('SocksVersion')]
[int[]]
$Version = @(4, 5),
# TODO: allow array of creds
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('USERPASS', 'SocksCredential')]
[pscredential]
$Credential,
# TODO: should I delete and just have $Credential mean USERPASS
# I don't think i'm planning to do GSSAPI
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet('NOAUTH', 'GSSAPI', 'USERPASS')]
[Alias('Method', 'Authentication', 'AcceptedMethod')]
[string[]]
$AcceptedMethods = @("NOAUTH")
)
# Get proxy request (returns full request if Socks4, else Socks5 initial message)
$SocksRequest = Read-SocksRequest $ClientStream
# Reject request if wrong Socks version
if ($Version -notcontains $SocksRequest.Version) {
Write-Verbose "Client requested Socks $($SocksRequest.Version) but only Socks $Version was allowed"
if ($SocksRequest.Version -eq 4) {
Write-Socks4Response $ClientStream -Reject
}
else {
Write-Socks5MessageReply $ClientStream -Reject
}
Write-Verbose "[-] Client rejected"
return
}
# Socks5 is its own thing
if ($SocksRequest.Version -eq 5) {
$Socks5Message = $SocksRequest
Start-Socks5Connection $ClientStream $Socks5Message -Credential $Credential -AcceptedMethods $AcceptedMethods
return
}
# Otherwise, connect to destination and send response accepting request
Write-Host "[_] Tunneling client to $($SocksRequest.DestinationAddress)`:$($SocksRequest.DestinationPort)"
$ProxyDestination = New-Object System.Net.Sockets.TcpClient($SocksRequest.DestinationAddress, $SocksRequest.DestinationPort)
if ($ProxyDestination.Connected) {
Write-Socks4Response $ClientStream
}
# Reject if connection failed
else {
Write-Host "[!] Connection FAILED!"
Write-Socks4Response $ClientStream -Reject
return
}
$ProxyDestinationStream = $ProxyDestination.GetStream()
# Start Forwarding
Connect-TcpStreams $ClientStream $ProxyDestinationStream
return
}
function Read-SocksRequest {
<#
.SYNOPSIS
Reads initial SOCKS message. For SOCKS 4, this is the request. For SOCKS 5 this is negotiation message.
#>
[CMDletBinding()]
param (
# Client TCP stream
[Parameter(Mandatory = $True, Position = 0, ValueFromPipelineByPropertyName = $true)]
$ClientStream
)
$Buffer = New-Object System.Byte[] 32
# NOTE: NetworkStream Read/Write has signature: (byte[] buffer, int offset, int size)
$ClientStream.Read($Buffer, 0, 1) | Out-Null
# Socks version
$Version = $Buffer[0]
if ($Version -eq 4) {
# Read request
$SocksRequest = Read-Socks4Request $ClientStream
}
elseif ($Version -eq 5) {
# Read initial message indicating client's desired auth methods
$Socks5Message = Read-Socks5Message $ClientStream
$SocksRequest = $Socks5Message
}
$SocksRequest
}
##########
# SOCKS-4 functions
#####
function Read-Socks4Request {
<#
.SYNOPSIS
Reads SOCKS 4 request from stream. 1 bit already read to determine version.
#>
[CMDletBinding()]
param (
# Client TCP stream, with 1 byte already read (version)
[Parameter(Mandatory = $True, Position = 0, ValueFromPipelineByPropertyName = $true)]
$ClientStream
)
$Version = 4
# Buffer for reading from ClientStream
$Buffer = New-Object System.Byte[] 32
# Read known parts of message (7 bytes b/c already read version)
$ClientStream.Read($Buffer, 0, 7) | Out-Null
# Parse CD
if ($Buffer[0] -eq 1) {
$Command = 'CONNECT'
}
elseif ($Buffer[0] -eq 2) {
$Command = 'BIND'
}
else {
$Command = $null
}
# Parse DSTPORT
$DestPort = ($Buffer[1] * 256) + $Buffer[2]
# Parse DSTIP (IPv4 only)
[Byte[]] $AddressBytes = $Buffer[3..6]
$DestAddress = New-Object System.Net.IPAddress(, $AddressBytes)
# Read and parse USERID (null-byte delimited)
for ($i = 0; $i -le ($Buffer.Length - 1); $i++) {
$ClientStream.Read($Buffer, $i, 1) | Out-Null
Write-Host $Buffer[$i]
if ($Buffer[$i] -eq 0) {
$UserID = [System.Text.Encoding]::ascii.GetString($Buffer[0..$i])
break
}
}
# Instantiate some object
$Socks4Request = new-object psobject -property @{
ClientStream = $ClientStream
Version = $Version