-
-
Notifications
You must be signed in to change notification settings - Fork 979
Expand file tree
/
Copy pathChannelForwardedTcpip.cs
More file actions
477 lines (414 loc) · 16 KB
/
ChannelForwardedTcpip.cs
File metadata and controls
477 lines (414 loc) · 16 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
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet.Channels
{
/// <summary>
/// Implements "forwarded-tcpip" SSH channel.
/// </summary>
internal class ChannelForwardedTcpip : ServerChannel, IChannelForwardedTcpip
{
private readonly object _socketShutdownAndCloseLock = new object();
private Socket _socket;
private IForwardedPort _forwardedPort;
private bool doSocks;
private bool doSocks5;
private ManualResetEvent completionWaitHandle;
/// <summary>
/// Initializes a new <see cref="ChannelForwardedTcpip"/> instance.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="localChannelNumber">The local channel number.</param>
/// <param name="localWindowSize">Size of the window.</param>
/// <param name="localPacketSize">Size of the packet.</param>
/// <param name="remoteChannelNumber">The remote channel number.</param>
/// <param name="remoteWindowSize">The window size of the remote party.</param>
/// <param name="remotePacketSize">The maximum size of a data packet that we can send to the remote party.</param>
internal ChannelForwardedTcpip(ISession session,
uint localChannelNumber,
uint localWindowSize,
uint localPacketSize,
uint remoteChannelNumber,
uint remoteWindowSize,
uint remotePacketSize)
: base(session,
localChannelNumber,
localWindowSize,
localPacketSize,
remoteChannelNumber,
remoteWindowSize,
remotePacketSize)
{
}
/// <summary>
/// Gets the type of the channel.
/// </summary>
/// <value>
/// The type of the channel.
/// </value>
public override ChannelTypes ChannelType
{
get { return ChannelTypes.ForwardedTcpip; }
}
/// <summary>
/// Binds the channel to the specified endpoint.
/// </summary>
/// <param name="remoteEndpoint">The endpoint to connect to.</param>
/// <param name="forwardedPort">The forwarded port for which the channel is opened.</param>
public void Bind(IPEndPoint remoteEndpoint, IForwardedPort forwardedPort)
{
if (!IsConnected)
{
throw new SshException("Session is not connected.");
}
_forwardedPort = forwardedPort;
_forwardedPort.Closing += ForwardedPort_Closing;
if (remoteEndpoint == null)
{
doSocks = true;
SendMessage(new ChannelOpenConfirmationMessage(RemoteChannelNumber, LocalWindowSize, LocalPacketSize, LocalChannelNumber));
completionWaitHandle = new ManualResetEvent(false);
completionWaitHandle.WaitOne();
completionWaitHandle.Dispose();
}
// Try to connect to the socket
try
{
_socket = SocketAbstraction.Connect(remoteEndpoint, ConnectionInfo.Timeout);
// send channel open confirmation message
SendMessage(new ChannelOpenConfirmationMessage(RemoteChannelNumber, LocalWindowSize, LocalPacketSize, LocalChannelNumber));
}
catch (Exception exp)
{
// send channel open failure message
SendMessage(new ChannelOpenFailureMessage(RemoteChannelNumber, exp.ToString(), ChannelOpenFailureMessage.ConnectFailed, "en"));
throw;
}
var buffer = new byte[RemotePacketSize];
SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
}
protected override void OnErrorOccured(Exception exp)
{
base.OnErrorOccured(exp);
// signal to the server that we will not send anything anymore; this will also interrupt the
// blocking receive in Bind if the server sends FIN/ACK in time
//
// if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
ShutdownSocket(SocketShutdown.Send);
}
/// <summary>
/// Occurs as the forwarded port is being stopped.
/// </summary>
private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
{
// signal to the server that we will not send anything anymore; this will also interrupt the
// blocking receive in Bind if the server sends FIN/ACK in time
//
// if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
ShutdownSocket(SocketShutdown.Send);
if (completionWaitHandle != null)
{
completionWaitHandle.Set();
}
}
/// <summary>
/// Shuts down the socket.
/// </summary>
/// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
private void ShutdownSocket(SocketShutdown how)
{
if (_socket == null)
return;
lock (_socketShutdownAndCloseLock)
{
var socket = _socket;
if (!socket.IsConnected())
return;
try
{
socket.Shutdown(how);
}
catch (SocketException ex)
{
// TODO: log as warning
DiagnosticAbstraction.Log("Failure shutting down socket: " + ex);
}
}
}
/// <summary>
/// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind(IPEndPoint,IForwardedPort)"/>.
/// </summary>
private void CloseSocket()
{
if (_socket == null)
return;
lock (_socketShutdownAndCloseLock)
{
var socket = _socket;
if (socket != null)
{
_socket = null;
socket.Dispose();
}
}
}
/// <summary>
/// Closes the channel waiting for the SSH_MSG_CHANNEL_CLOSE message to be received from the server.
/// </summary>
protected override void Close()
{
var forwardedPort = _forwardedPort;
if (forwardedPort != null)
{
forwardedPort.Closing -= ForwardedPort_Closing;
_forwardedPort = null;
}
// signal to the server that we will not send anything anymore; this will also interrupt the
// blocking receive in Bind if the server sends FIN/ACK in time
//
// if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
ShutdownSocket(SocketShutdown.Send);
// close the SSH channel, and mark the channel closed
base.Close();
// close the socket
CloseSocket();
}
/// <summary>
/// Called when channel data is received.
/// </summary>
/// <param name="data">The data.</param>
protected override void OnData(byte[] data)
{
if (doSocks)
{
var stream = new MemoryStream(data);
HandleSocks(stream);
return;
}
base.OnData(data);
var socket = _socket;
if (socket.IsConnected())
{
SocketAbstraction.Send(socket, data, 0, data.Length);
}
}
private void HandleSocks(MemoryStream stream)
{
var version = ReadByte(stream);
switch (version)
{
case 4:
HandleSocks4(stream);
doSocks = false;
return;
case 5:
if (!doSocks5)
{
var authenticationMethodsCount = ReadByte(stream);
var authenticationMethods = new byte[authenticationMethodsCount];
if (stream.Read(authenticationMethods, 0, authenticationMethods.Length) == 0)
{
return;
}
if (authenticationMethods.Min() == 0)
{
// no user authentication is one of the authentication methods supported
// by the SOCKS client
SendData(new byte[] { 0x05, 0x00 });
}
else
{
// the SOCKS client requires authentication, which we currently do not support
SendData(new byte[] { 0x05, 0xFF });
}
doSocks5 = true;
return;
}
HandleSocks5(stream);
doSocks = false;
return;
}
throw new NotSupportedException(string.Format("SOCKS version {0} is not supported.", version));
}
private void HandleSocks4(MemoryStream stream)
{
var commandCode = ReadByte(stream);
if (commandCode == -1)
{
return;
}
var portBuffer = new byte[2];
if (stream.Read(portBuffer, 0, portBuffer.Length) == 0)
{
return;
}
var port = (portBuffer[0] * 256 + portBuffer[1]);
var ipBuffer = new byte[4];
if (stream.Read(ipBuffer, 0, ipBuffer.Length) == 0)
{
return;
}
var ipAddress = new IPAddress(ipBuffer);
ThreadAbstraction.ExecuteThread(() =>
{
var endpoint = new IPEndPoint(ipAddress, port);
try
{
_socket = SocketAbstraction.Connect(endpoint, ConnectionInfo.Timeout);
}
catch (Exception exp)
{
// send channel open failure message
SendMessage(new ChannelOpenFailureMessage(RemoteChannelNumber, exp.ToString(), ChannelOpenFailureMessage.ConnectFailed, "en"));
completionWaitHandle.Set();
throw;
}
SendData(new byte[] { 0x00, 0x5a });
SendData(portBuffer);
SendData(ipBuffer);
var buffer = new byte[RemotePacketSize];
SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
});
}
private void HandleSocks5(MemoryStream stream)
{
var commandCode = ReadByte(stream);
if (commandCode == -1)
{
return;
}
var reserved = ReadByte(stream);
if (reserved == -1)
{
return;
}
if (reserved != 0)
{
throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
}
var addressType = ReadByte(stream);
if (addressType == -1)
{
// SOCKS client closed connection
return;
}
var ipAddress = GetSocks5Host(addressType, stream);
if (ipAddress == null)
{
// SOCKS client closed connection
return;
}
var portBuffer = new byte[2];
if (stream.Read(portBuffer, 0, portBuffer.Length) == 0)
{
return;
}
var port = (portBuffer[0] * 256 + portBuffer[1]);
ThreadAbstraction.ExecuteThread(() =>
{
var endpoint = new IPEndPoint(ipAddress, port);
try
{
_socket = SocketAbstraction.Connect(endpoint, ConnectionInfo.Timeout);
}
catch
{
// send channel open failure message
SendData(CreateSocks5Reply(false));
completionWaitHandle.Set();
throw;
}
SendData(CreateSocks5Reply(true));
var buffer = new byte[RemotePacketSize];
SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
});
}
private IPAddress GetSocks5Host(int addressType, MemoryStream stream)
{
switch (addressType)
{
case 0x01: // IPv4
{
var addressBuffer = new byte[4];
if (stream.Read(addressBuffer, 0, 4) == 0)
{
// SOCKS client closed connection
return null;
}
return new IPAddress(addressBuffer);
}
case 0x03: // Domain name
{
var length = ReadByte(stream);
if (length == -1)
{
// SOCKS client closed connection
return null;
}
var addressBuffer = new byte[length];
if (stream.Read(addressBuffer, 0, addressBuffer.Length) == 0)
{
// SOCKS client closed connection
return null;
}
var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length);
return DnsAbstraction.GetHostAddresses(hostName)[0];
}
case 0x04: // IPv6
{
var addressBuffer = new byte[16];
if (stream.Read(addressBuffer, 0, 16) == 0)
{
return null;
}
return new IPAddress(addressBuffer);
}
default:
throw new ProxyException(string.Format("SOCKS5: Address type '{0}' is not supported.", addressType));
}
}
private static byte[] CreateSocks5Reply(bool success)
{
var socksReply = new byte[
// SOCKS version
1 +
// Reply field
1 +
// Reserved; fixed: 0x00
1 +
// Address type; fixed: 0x01
1 +
// IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00}
4 +
// server bound port; fixed: {0x00, 0x00}
2];
socksReply[0] = 0x05;
if (success)
{
socksReply[1] = 0x00; // succeeded
}
else
{
socksReply[1] = 0x01; // general SOCKS server failure
}
// reserved
socksReply[2] = 0x00;
// IPv4 address type
socksReply[3] = 0x01;
return socksReply;
}
private int ReadByte(MemoryStream stream)
{
var buffer = new byte[1];
if (stream.Read(buffer, 0, 1) == 0)
return -1;
return buffer[0];
}
}
}