-
Notifications
You must be signed in to change notification settings - Fork 11
/
LocalForwardTests.cs
256 lines (210 loc) · 10.5 KB
/
LocalForwardTests.cs
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
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Xunit;
namespace Tmds.Ssh.Tests;
[Collection(nameof(SshServerCollection))]
public class LocalForwardTests
{
const int SocatStartDelay = 100;
private readonly SshServer _sshServer;
public LocalForwardTests(SshServer sshServer)
{
_sshServer = sshServer;
}
[Fact]
public async Task ForwardsTcp()
{
using var client = await _sshServer.CreateClientAsync();
// start a an echo server using socat.
const int socatPort = 1234;
using var soCatProcess = await client.ExecuteAsync($"socat -v tcp-l:{socatPort},fork exec:'/bin/cat'");
await Task.Delay(SocatStartDelay); // wait a little for socat to start.
using var directForward = await client.StartForwardAsync(new IPEndPoint(IPAddress.Loopback, 0), new RemoteHostEndPoint("localhost", socatPort));
await AssertForwards(directForward);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ForwardsSocks(bool useIP)
{
using var client = await _sshServer.CreateClientAsync();
// start a an echo server using socat.
const int socatPort = 1234;
using var soCatProcess = await client.ExecuteAsync($"socat -v tcp-l:{socatPort},fork exec:'/bin/cat'");
await Task.Delay(SocatStartDelay); // wait a little for socat to start.
using var socksForward = await client.StartSocksForward(new IPEndPoint(IPAddress.Loopback, 0));
await AssertForwards(socksForward, useIP ? IPAddress.Loopback : null, useIP ? null : "localhost", socatPort);
}
[Fact]
public async Task ForwardsUnix()
{
using var client = await _sshServer.CreateClientAsync();
// start a an echo server using socat.
const string socketPath = "/tmp/mysocket";
using var soCatProcess = await client.ExecuteAsync($"socat -v unix-l:{socketPath},fork exec:'/bin/cat'");
await Task.Delay(SocatStartDelay); // wait a little for socat to start.
using var directForward = await client.StartForwardAsync(new IPEndPoint(IPAddress.Loopback, 0), new RemoteUnixEndPoint(socketPath));
await AssertForwards(directForward);
}
[Fact]
public async Task BindUnixSocket()
{
using var client = await _sshServer.CreateClientAsync();
// start a an echo server using socat.
const int socatPort = 1234;
using var soCatProcess = await client.ExecuteAsync($"socat -v tcp-l:{socatPort},fork exec:'/bin/cat'");
await Task.Delay(SocatStartDelay); // wait a little for socat to start.
var ep = new UnixDomainSocketEndPoint(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
using var directForward = await client.StartForwardAsync(ep, new RemoteHostEndPoint("localhost", socatPort));
await AssertForwards(directForward);
}
private async Task AssertForwards(DirectForward directForward)
{
byte[] helloWorldBytes = Encoding.UTF8.GetBytes("hello world");
byte[] receiveBuffer = new byte[128];
for (int i = 0; i < 2; i++)
{
EndPoint endPoint = directForward.LocalEndPoint!;
using var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, endPoint.AddressFamily == AddressFamily.InterNetwork ? ProtocolType.Tcp : ProtocolType.Unspecified);
if (socket.ProtocolType == ProtocolType.Tcp)
{
socket.NoDelay = true;
}
await socket.ConnectAsync(endPoint);
for (int j = 0; j < 2; j++)
{
await socket.SendAsync(helloWorldBytes);
int bytesRead = await socket.ReceiveAsync(receiveBuffer);
Assert.Equal(helloWorldBytes.Length, bytesRead);
Assert.Equal(helloWorldBytes, receiveBuffer.AsSpan(0, bytesRead).ToArray());
}
socket.Shutdown(SocketShutdown.Send);
int received = await socket.ReceiveAsync(receiveBuffer);
Assert.Equal(0, received);
}
}
private async Task AssertForwards(SocksForward socksForward, IPAddress? remoteIP, string? remoteHost, int remotePort)
{
byte[] helloWorldBytes = Encoding.UTF8.GetBytes("hello world");
byte[] receiveBuffer = new byte[128];
EndPoint endPoint = socksForward.LocalEndPoint!;
using var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, endPoint.AddressFamily == AddressFamily.InterNetwork ? ProtocolType.Tcp : ProtocolType.Unspecified);
if (socket.ProtocolType == ProtocolType.Tcp)
{
socket.NoDelay = true;
}
await socket.ConnectAsync(endPoint);
await DoSocksConnectAsync(socket, remoteIP, remoteHost, remotePort);
await socket.SendAsync(helloWorldBytes);
int bytesRead = await socket.ReceiveAsync(receiveBuffer);
Assert.Equal(helloWorldBytes.Length, bytesRead);
Assert.Equal(helloWorldBytes, receiveBuffer.AsSpan(0, bytesRead).ToArray());
socket.Shutdown(SocketShutdown.Send);
int received = await socket.ReceiveAsync(receiveBuffer);
Assert.Equal(0, received);
}
private async Task DoSocksConnectAsync(Socket socket, IPAddress? remoteIP, string? remoteHost, int remotePort)
{
byte[] buffer = new byte[512];
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
await socket.SendAsync(new byte[] { 5, 2, 0, 1 }); // V5 No Auth or GSSAPI auth.
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
int bytesRead = await socket.ReceiveAsync(buffer.AsMemory(0, 2));
Assert.Equal(2, bytesRead);
Assert.Equal(5, buffer[0]); // v5
Assert.Equal(0, buffer[1]); // no auth
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
buffer[0] = 5;
buffer[1] = 1;
buffer[2] = 0;
int portOffset = 0;
if (remoteIP is not null && remoteIP.AddressFamily == AddressFamily.InterNetwork)
{
buffer[3] = 1; // IPv4
remoteIP.TryWriteBytes(buffer.AsSpan(4), out _);
portOffset = 8;
}
else if (remoteIP is not null && remoteIP.AddressFamily == AddressFamily.InterNetwork)
{
buffer[3] = 4; // IPv6
remoteIP.TryWriteBytes(buffer.AsSpan(4), out _);
portOffset = 20;
}
else
{
Assert.NotNull(remoteHost);
buffer[3] = 3; // Domain name
int bytesWritten = Encoding.UTF8.GetBytes(remoteHost, buffer.AsSpan(5));
buffer[4] = (byte)bytesWritten;
portOffset = 5 + bytesWritten;
}
buffer[portOffset++] = (byte)(remotePort >> 8);
buffer[portOffset++] = (byte)remotePort;
await socket.SendAsync(buffer.AsMemory(0, portOffset));
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
bytesRead = await socket.ReceiveAsync(buffer.AsMemory(0, 10));
// note: the implementation is always replying with 0.0.0.0:0.
Assert.Equal(10, bytesRead);
Assert.Equal(new byte[] { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, buffer.AsMemory(0, 10).ToArray());
}
[Fact]
public async Task StopsWhenDisposed()
{
using var client = await _sshServer.CreateClientAsync();
using var directForward = await client.StartForwardAsync(new IPEndPoint(IPAddress.Loopback, 0), new RemoteHostEndPoint("localhost", 5000));
CancellationToken ct = directForward.Stopped;
EndPoint? endPoint = directForward.LocalEndPoint;
Assert.False(ct.IsCancellationRequested);
Assert.NotNull(endPoint);
directForward.Dispose();
Assert.True(ct.IsCancellationRequested);
Assert.Throws<ObjectDisposedException>(() => directForward.LocalEndPoint);
Assert.Throws<ObjectDisposedException>(() => directForward.Stopped);
Assert.Throws<ObjectDisposedException>(() => directForward.ThrowIfStopped());
using var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
await Assert.ThrowsAnyAsync<SocketException>(async () => await socket.ConnectAsync(endPoint));
}
[Fact]
public async Task StopsWhenClientDisconnects()
{
using var client = await _sshServer.CreateClientAsync();
using var directForward = await client.StartForwardAsync(new IPEndPoint(IPAddress.Loopback, 0), new RemoteHostEndPoint("localhost", 5000));
CancellationToken ct = directForward.Stopped;
EndPoint? endPoint = directForward.LocalEndPoint;
Assert.False(ct.IsCancellationRequested);
Assert.NotNull(endPoint);
client.Dispose();
Assert.True(ct.IsCancellationRequested);
Assert.Throws<SshConnectionClosedException>(() => directForward.LocalEndPoint);
Assert.True(directForward.Stopped.IsCancellationRequested);
Assert.Throws<SshConnectionClosedException>(() => directForward.ThrowIfStopped());
using var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
await Assert.ThrowsAnyAsync<SocketException>(async () => await socket.ConnectAsync(endPoint));
}
[Fact]
public async Task IPv6IsDualMode()
{
using var client = await _sshServer.CreateClientAsync();
using var directForward = await client.StartForwardAsync(new IPEndPoint(IPAddress.IPv6Any, 0), new RemoteHostEndPoint("nowhere", 10));
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, (directForward.LocalEndPoint as IPEndPoint)!.Port));
}
}