ForwardedPortDynamic.NET.cs 20 KB

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