ForwardedPortDynamic.NET.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using Renci.SshNet.Abstractions;
  8. using Renci.SshNet.Channels;
  9. using Renci.SshNet.Common;
  10. namespace Renci.SshNet
  11. {
  12. public partial class ForwardedPortDynamic
  13. {
  14. private Socket _listener;
  15. private CountdownEvent _pendingChannelCountdown;
  16. partial void InternalStart()
  17. {
  18. InitializePendingChannelCountdown();
  19. var ip = IPAddress.Any;
  20. if (!string.IsNullOrEmpty(BoundHost))
  21. {
  22. ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
  23. }
  24. var ep = new IPEndPoint(ip, (int) BoundPort);
  25. _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) {NoDelay = true};
  26. _listener.Bind(ep);
  27. _listener.Listen(5);
  28. Session.ErrorOccured += Session_ErrorOccured;
  29. Session.Disconnected += Session_Disconnected;
  30. // consider port started when we're listening for inbound connections
  31. _status = ForwardedPortStatus.Started;
  32. StartAccept(null);
  33. }
  34. private void StartAccept(SocketAsyncEventArgs e)
  35. {
  36. if (e == null)
  37. {
  38. e = new SocketAsyncEventArgs();
  39. e.Completed += AcceptCompleted;
  40. }
  41. else
  42. {
  43. // clear the socket as we're reusing the context object
  44. e.AcceptSocket = null;
  45. }
  46. // only accept new connections while we are started
  47. if (IsStarted)
  48. {
  49. try
  50. {
  51. if (!_listener.AcceptAsync(e))
  52. {
  53. AcceptCompleted(null, e);
  54. }
  55. }
  56. catch (ObjectDisposedException)
  57. {
  58. if (_status == ForwardedPortStatus.Stopped || _status == ForwardedPortStatus.Stopped)
  59. {
  60. // ignore ObjectDisposedException while stopping or stopped
  61. return;
  62. }
  63. throw;
  64. }
  65. }
  66. }
  67. private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
  68. {
  69. if (e.SocketError == SocketError.OperationAborted || e.SocketError == SocketError.NotSocket)
  70. {
  71. // server was stopped
  72. return;
  73. }
  74. // capture client socket
  75. var clientSocket = e.AcceptSocket;
  76. if (e.SocketError != SocketError.Success)
  77. {
  78. // accept new connection
  79. StartAccept(e);
  80. // dispose broken client socket
  81. CloseClientSocket(clientSocket);
  82. return;
  83. }
  84. // accept new connection
  85. StartAccept(e);
  86. // process connection
  87. ProcessAccept(clientSocket);
  88. }
  89. private void ProcessAccept(Socket clientSocket)
  90. {
  91. // close the client socket if we're no longer accepting new connections
  92. if (!IsStarted)
  93. {
  94. CloseClientSocket(clientSocket);
  95. return;
  96. }
  97. // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling
  98. // that same instance; the instance field for the countdown event is re-initialized when the port is restarted
  99. // and at that time there may still be pending requests
  100. var pendingChannelCountdown = _pendingChannelCountdown;
  101. pendingChannelCountdown.AddCount();
  102. try
  103. {
  104. using (var channel = Session.CreateChannelDirectTcpip())
  105. {
  106. channel.Exception += Channel_Exception;
  107. if (!HandleSocks(channel, clientSocket, Session.ConnectionInfo.Timeout))
  108. {
  109. CloseClientSocket(clientSocket);
  110. return;
  111. }
  112. // start receiving from client socket (and sending to server)
  113. channel.Bind();
  114. }
  115. }
  116. catch (Exception exp)
  117. {
  118. RaiseExceptionEvent(exp);
  119. CloseClientSocket(clientSocket);
  120. }
  121. finally
  122. {
  123. // take into account that CountdownEvent has since been disposed; when stopping the port we
  124. // wait for a given time for the channels to close, but once that timeout period has elapsed
  125. // the CountdownEvent will be disposed
  126. try
  127. {
  128. pendingChannelCountdown.Signal();
  129. }
  130. catch (ObjectDisposedException)
  131. {
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Initializes the <see cref="CountdownEvent"/>.
  137. /// </summary>
  138. /// <remarks>
  139. /// <para>
  140. /// When the port is started for the first time, a <see cref="CountdownEvent"/> is created with an initial count
  141. /// of <c>1</c>.
  142. /// </para>
  143. /// <para>
  144. /// On subsequent (re)starts, we'll dispose the current <see cref="CountdownEvent"/> and create a new one with
  145. /// initial count of <c>1</c>.
  146. /// </para>
  147. /// </remarks>
  148. private void InitializePendingChannelCountdown()
  149. {
  150. var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1));
  151. if (original != null)
  152. {
  153. original.Dispose();
  154. }
  155. }
  156. private bool HandleSocks(IChannelDirectTcpip channel, Socket clientSocket, TimeSpan timeout)
  157. {
  158. // create eventhandler which is to be invoked to interrupt a blocking receive
  159. // when we're closing the forwarded port
  160. EventHandler closeClientSocket = (_, args) => CloseClientSocket(clientSocket);
  161. Closing += closeClientSocket;
  162. try
  163. {
  164. var version = SocketAbstraction.ReadByte(clientSocket, timeout);
  165. switch (version)
  166. {
  167. case -1:
  168. // SOCKS client closed connection
  169. return false;
  170. case 4:
  171. return HandleSocks4(clientSocket, channel, timeout);
  172. case 5:
  173. return HandleSocks5(clientSocket, channel, timeout);
  174. default:
  175. throw new NotSupportedException(string.Format("SOCKS version {0} is not supported.", version));
  176. }
  177. }
  178. catch (SocketException ex)
  179. {
  180. // ignore exception thrown by interrupting the blocking receive as part of closing
  181. // the forwarded port
  182. #if NETFRAMEWORK
  183. if (ex.SocketErrorCode != SocketError.Interrupted)
  184. {
  185. RaiseExceptionEvent(ex);
  186. }
  187. #else
  188. // Since .NET 5 the exception has been changed.
  189. // more info https://github.com/dotnet/runtime/issues/41585
  190. if (ex.SocketErrorCode != SocketError.ConnectionAborted)
  191. {
  192. RaiseExceptionEvent(ex);
  193. }
  194. #endif
  195. return false;
  196. }
  197. finally
  198. {
  199. // interrupt of blocking receive is now handled by channel (SOCKS4 and SOCKS5)
  200. // or no longer necessary
  201. Closing -= closeClientSocket;
  202. }
  203. }
  204. private static void CloseClientSocket(Socket clientSocket)
  205. {
  206. if (clientSocket.Connected)
  207. {
  208. try
  209. {
  210. clientSocket.Shutdown(SocketShutdown.Send);
  211. }
  212. catch (Exception)
  213. {
  214. // ignore exception when client socket was already closed
  215. }
  216. }
  217. clientSocket.Dispose();
  218. }
  219. /// <summary>
  220. /// Interrupts the listener, and unsubscribes from <see cref="Session"/> events.
  221. /// </summary>
  222. partial void StopListener()
  223. {
  224. // close listener socket
  225. var listener = _listener;
  226. if (listener != null)
  227. {
  228. listener.Dispose();
  229. }
  230. // unsubscribe from session events
  231. var session = Session;
  232. if (session != null)
  233. {
  234. session.ErrorOccured -= Session_ErrorOccured;
  235. session.Disconnected -= Session_Disconnected;
  236. }
  237. }
  238. /// <summary>
  239. /// Waits for pending channels to close.
  240. /// </summary>
  241. /// <param name="timeout">The maximum time to wait for the pending channels to close.</param>
  242. partial void InternalStop(TimeSpan timeout)
  243. {
  244. _pendingChannelCountdown.Signal();
  245. if (!_pendingChannelCountdown.Wait(timeout))
  246. {
  247. // TODO: log as warning
  248. DiagnosticAbstraction.Log("Timeout waiting for pending channels in dynamic forwarded port to close.");
  249. }
  250. }
  251. partial void InternalDispose(bool disposing)
  252. {
  253. if (disposing)
  254. {
  255. var listener = _listener;
  256. if (listener != null)
  257. {
  258. _listener = null;
  259. listener.Dispose();
  260. }
  261. var pendingRequestsCountdown = _pendingChannelCountdown;
  262. if (pendingRequestsCountdown != null)
  263. {
  264. _pendingChannelCountdown = null;
  265. pendingRequestsCountdown.Dispose();
  266. }
  267. }
  268. }
  269. private void Session_Disconnected(object sender, EventArgs e)
  270. {
  271. var session = Session;
  272. if (session != null)
  273. {
  274. StopPort(session.ConnectionInfo.Timeout);
  275. }
  276. }
  277. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  278. {
  279. var session = Session;
  280. if (session != null)
  281. {
  282. StopPort(session.ConnectionInfo.Timeout);
  283. }
  284. }
  285. private void Channel_Exception(object sender, ExceptionEventArgs e)
  286. {
  287. RaiseExceptionEvent(e.Exception);
  288. }
  289. private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  290. {
  291. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  292. if (commandCode == -1)
  293. {
  294. // SOCKS client closed connection
  295. return false;
  296. }
  297. // TODO: See what need to be done depends on the code
  298. var portBuffer = new byte[2];
  299. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  300. {
  301. // SOCKS client closed connection
  302. return false;
  303. }
  304. var port = Pack.BigEndianToUInt16(portBuffer);
  305. var ipBuffer = new byte[4];
  306. if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0)
  307. {
  308. // SOCKS client closed connection
  309. return false;
  310. }
  311. var ipAddress = new IPAddress(ipBuffer);
  312. var username = ReadString(socket, timeout);
  313. if (username == null)
  314. {
  315. // SOCKS client closed connection
  316. return false;
  317. }
  318. var host = ipAddress.ToString();
  319. RaiseRequestReceived(host, port);
  320. channel.Open(host, port, this, socket);
  321. SocketAbstraction.SendByte(socket, 0x00);
  322. if (channel.IsOpen)
  323. {
  324. SocketAbstraction.SendByte(socket, 0x5a);
  325. SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
  326. SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length);
  327. return true;
  328. }
  329. // signal that request was rejected or failed
  330. SocketAbstraction.SendByte(socket, 0x5b);
  331. return false;
  332. }
  333. private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  334. {
  335. var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout);
  336. if (authenticationMethodsCount == -1)
  337. {
  338. // SOCKS client closed connection
  339. return false;
  340. }
  341. var authenticationMethods = new byte[authenticationMethodsCount];
  342. if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0)
  343. {
  344. // SOCKS client closed connection
  345. return false;
  346. }
  347. if (authenticationMethods.Min() == 0)
  348. {
  349. // no user authentication is one of the authentication methods supported
  350. // by the SOCKS client
  351. SocketAbstraction.Send(socket, new byte[] {0x05, 0x00}, 0, 2);
  352. }
  353. else
  354. {
  355. // the SOCKS client requires authentication, which we currently do not support
  356. SocketAbstraction.Send(socket, new byte[] {0x05, 0xFF}, 0, 2);
  357. // we continue business as usual but expect the client to close the connection
  358. // so one of the subsequent reads should return -1 signaling that the client
  359. // has effectively closed the connection
  360. }
  361. var version = SocketAbstraction.ReadByte(socket, timeout);
  362. if (version == -1)
  363. {
  364. // SOCKS client closed connection
  365. return false;
  366. }
  367. if (version != 5)
  368. throw new ProxyException("SOCKS5: Version 5 is expected.");
  369. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  370. if (commandCode == -1)
  371. {
  372. // SOCKS client closed connection
  373. return false;
  374. }
  375. var reserved = SocketAbstraction.ReadByte(socket, timeout);
  376. if (reserved == -1)
  377. {
  378. // SOCKS client closed connection
  379. return false;
  380. }
  381. if (reserved != 0)
  382. {
  383. throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
  384. }
  385. var addressType = SocketAbstraction.ReadByte(socket, timeout);
  386. if (addressType == -1)
  387. {
  388. // SOCKS client closed connection
  389. return false;
  390. }
  391. var host = GetSocks5Host(addressType, socket, timeout);
  392. if (host == null)
  393. {
  394. // SOCKS client closed connection
  395. return false;
  396. }
  397. var portBuffer = new byte[2];
  398. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  399. {
  400. // SOCKS client closed connection
  401. return false;
  402. }
  403. var port = Pack.BigEndianToUInt16(portBuffer);
  404. RaiseRequestReceived(host, port);
  405. channel.Open(host, port, this, socket);
  406. var socksReply = CreateSocks5Reply(channel.IsOpen);
  407. SocketAbstraction.Send(socket, socksReply, 0, socksReply.Length);
  408. return true;
  409. }
  410. private static string GetSocks5Host(int addressType, Socket socket, TimeSpan timeout)
  411. {
  412. switch (addressType)
  413. {
  414. case 0x01: // IPv4
  415. {
  416. var addressBuffer = new byte[4];
  417. if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0)
  418. {
  419. // SOCKS client closed connection
  420. return null;
  421. }
  422. var ipv4 = new IPAddress(addressBuffer);
  423. return ipv4.ToString();
  424. }
  425. case 0x03: // Domain name
  426. {
  427. var length = SocketAbstraction.ReadByte(socket, timeout);
  428. if (length == -1)
  429. {
  430. // SOCKS client closed connection
  431. return null;
  432. }
  433. var addressBuffer = new byte[length];
  434. if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0)
  435. {
  436. // SOCKS client closed connection
  437. return null;
  438. }
  439. var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length);
  440. return hostName;
  441. }
  442. case 0x04: // IPv6
  443. {
  444. var addressBuffer = new byte[16];
  445. if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0)
  446. {
  447. // SOCKS client closed connection
  448. return null;
  449. }
  450. var ipv6 = new IPAddress(addressBuffer);
  451. return ipv6.ToString();
  452. }
  453. default:
  454. throw new ProxyException(string.Format("SOCKS5: Address type '{0}' is not supported.", addressType));
  455. }
  456. }
  457. private static byte[] CreateSocks5Reply(bool channelOpen)
  458. {
  459. var socksReply = new byte
  460. [
  461. // SOCKS version
  462. 1 +
  463. // Reply field
  464. 1 +
  465. // Reserved; fixed: 0x00
  466. 1 +
  467. // Address type; fixed: 0x01
  468. 1 +
  469. // IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00}
  470. 4 +
  471. // server bound port; fixed: {0x00, 0x00}
  472. 2
  473. ];
  474. socksReply[0] = 0x05;
  475. if (channelOpen)
  476. {
  477. socksReply[1] = 0x00; // succeeded
  478. }
  479. else
  480. {
  481. socksReply[1] = 0x01; // general SOCKS server failure
  482. }
  483. // reserved
  484. socksReply[2] = 0x00;
  485. // IPv4 address type
  486. socksReply[3] = 0x01;
  487. return socksReply;
  488. }
  489. /// <summary>
  490. /// Reads a null terminated string from a socket.
  491. /// </summary>
  492. /// <param name="socket">The <see cref="Socket"/> to read from.</param>
  493. /// <param name="timeout">The timeout to apply to individual reads.</param>
  494. /// <returns>
  495. /// The <see cref="string"/> read, or <c>null</c> when the socket was closed.
  496. /// </returns>
  497. private static string ReadString(Socket socket, TimeSpan timeout)
  498. {
  499. var text = new StringBuilder();
  500. var buffer = new byte[1];
  501. while (true)
  502. {
  503. if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0)
  504. {
  505. // SOCKS client closed connection
  506. return null;
  507. }
  508. var byteRead = buffer[0];
  509. if (byteRead == 0)
  510. {
  511. // end of the string
  512. break;
  513. }
  514. var c = (char) byteRead;
  515. text.Append(c);
  516. }
  517. return text.ToString();
  518. }
  519. }
  520. }