-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPipe.ps1
More file actions
66 lines (56 loc) · 2.56 KB
/
TCPipe.ps1
File metadata and controls
66 lines (56 loc) · 2.56 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
function Start-TcpProxy {
param(
[int]$ListenPort,
[string]$RemoteHost,
[int]$RemotePort
)
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, $ListenPort)
$listener.Start()
# FIXED: Use string formatting
Write-Host ("Listening on 0.0.0.0:{0} -> {1}:{2}" -f $ListenPort, $RemoteHost, $RemotePort)
while ($true) {
$client = $listener.AcceptTcpClient()
Write-Host "Client connected: $($client.Client.RemoteEndPoint)"
Start-Job -ScriptBlock {
param($Client, $RemoteHost, $RemotePort)
try {
$remote = [System.Net.Sockets.TcpClient]::new($RemoteHost, $RemotePort)
$clientStream = $Client.GetStream()
$remoteStream = $remote.GetStream()
# Bidirectional forwarding
$clientToRemoteJob = Start-Job -ScriptBlock {
param($FromStream, $ToStream)
$buffer = New-Object byte[] 8192
try {
while (($bytesRead = $FromStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
$ToStream.Write($buffer, 0, $bytesRead)
$ToStream.Flush()
}
} catch { }
} -ArgumentList $clientStream, $remoteStream
$remoteToClientJob = Start-Job -ScriptBlock {
param($FromStream, $ToStream)
$buffer = New-Object byte[] 8192
try {
while (($bytesRead = $FromStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
$ToStream.Write($buffer, 0, $bytesRead)
$ToStream.Flush()
}
} catch { }
} -ArgumentList $remoteStream, $clientStream
# Wait for both forwarding jobs to complete
$clientToRemoteJob | Wait-Job | Out-Null
$remoteToClientJob | Wait-Job | Out-Null
# Clean up
$clientToRemoteJob | Remove-Job -Force
$remoteToClientJob | Remove-Job -Force
$Client.Close()
$remote.Close()
}
catch {
Write-Error "Error: $($_.Exception.Message)"
try { $Client.Close() } catch { }
}
} -ArgumentList $client, $RemoteHost, $RemotePort
}
}