ForwardedPortDynamic.NET.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 (ex.SocketErrorCode != SocketError.Interrupted)
  183. {
  184. RaiseExceptionEvent(ex);
  185. }
  186. return false;
  187. }
  188. finally
  189. {
  190. // interrupt of blocking receive is now handled by channel (SOCKS4 and SOCKS5)
  191. // or no longer necessary
  192. Closing -= closeClientSocket;
  193. }
  194. }
  195. private static void CloseClientSocket(Socket clientSocket)
  196. {
  197. if (clientSocket.Connected)
  198. {
  199. try
  200. {
  201. clientSocket.Shutdown(SocketShutdown.Send);
  202. }
  203. catch (Exception)
  204. {
  205. // ignore exception when client socket was already closed
  206. }
  207. }
  208. clientSocket.Dispose();
  209. }
  210. /// <summary>
  211. /// Interrupts the listener, and unsubscribes from <see cref="Session"/> events.
  212. /// </summary>
  213. partial void StopListener()
  214. {
  215. // close listener socket
  216. var listener = _listener;
  217. if (listener != null)
  218. {
  219. listener.Dispose();
  220. }
  221. // unsubscribe from session events
  222. var session = Session;
  223. if (session != null)
  224. {
  225. session.ErrorOccured -= Session_ErrorOccured;
  226. session.Disconnected -= Session_Disconnected;
  227. }
  228. }
  229. /// <summary>
  230. /// Waits for pending channels to close.
  231. /// </summary>
  232. /// <param name="timeout">The maximum time to wait for the pending channels to close.</param>
  233. partial void InternalStop(TimeSpan timeout)
  234. {
  235. _pendingChannelCountdown.Signal();
  236. _pendingChannelCountdown.Wait(timeout);
  237. }
  238. partial void InternalDispose(bool disposing)
  239. {
  240. if (disposing)
  241. {
  242. var listener = _listener;
  243. if (listener != null)
  244. {
  245. _listener = null;
  246. listener.Dispose();
  247. }
  248. var pendingRequestsCountdown = _pendingChannelCountdown;
  249. if (pendingRequestsCountdown != null)
  250. {
  251. _pendingChannelCountdown = null;
  252. pendingRequestsCountdown.Dispose();
  253. }
  254. }
  255. }
  256. private void Session_Disconnected(object sender, EventArgs e)
  257. {
  258. var session = Session;
  259. if (session != null)
  260. {
  261. StopPort(session.ConnectionInfo.Timeout);
  262. }
  263. }
  264. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  265. {
  266. var session = Session;
  267. if (session != null)
  268. {
  269. StopPort(session.ConnectionInfo.Timeout);
  270. }
  271. }
  272. private void Channel_Exception(object sender, ExceptionEventArgs e)
  273. {
  274. RaiseExceptionEvent(e.Exception);
  275. }
  276. private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  277. {
  278. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  279. if (commandCode == -1)
  280. {
  281. // SOCKS client closed connection
  282. return false;
  283. }
  284. // TODO: See what need to be done depends on the code
  285. var portBuffer = new byte[2];
  286. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  287. {
  288. // SOCKS client closed connection
  289. return false;
  290. }
  291. var port = (uint)(portBuffer[0] * 256 + portBuffer[1]);
  292. var ipBuffer = new byte[4];
  293. if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0)
  294. {
  295. // SOCKS client closed connection
  296. return false;
  297. }
  298. var ipAddress = new IPAddress(ipBuffer);
  299. var username = ReadString(socket, timeout);
  300. if (username == null)
  301. {
  302. // SOCKS client closed connection
  303. return false;
  304. }
  305. var host = ipAddress.ToString();
  306. RaiseRequestReceived(host, port);
  307. channel.Open(host, port, this, socket);
  308. SocketAbstraction.SendByte(socket, 0x00);
  309. if (channel.IsOpen)
  310. {
  311. SocketAbstraction.SendByte(socket, 0x5a);
  312. SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
  313. SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length);
  314. return true;
  315. }
  316. // signal that request was rejected or failed
  317. SocketAbstraction.SendByte(socket, 0x5b);
  318. return false;
  319. }
  320. private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  321. {
  322. var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout);
  323. if (authenticationMethodsCount == -1)
  324. {
  325. // SOCKS client closed connection
  326. return false;
  327. }
  328. var authenticationMethods = new byte[authenticationMethodsCount];
  329. if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0)
  330. {
  331. // SOCKS client closed connection
  332. return false;
  333. }
  334. if (authenticationMethods.Min() == 0)
  335. {
  336. // no user authentication is one of the authentication methods supported
  337. // by the SOCKS client
  338. SocketAbstraction.Send(socket, new byte[] { 0x05, 0x00 }, 0, 2);
  339. }
  340. else
  341. {
  342. // the SOCKS client requires authentication, which we currently do not support
  343. SocketAbstraction.Send(socket, new byte[] { 0x05, 0xFF }, 0, 2);
  344. // we continue business as usual but expect the client to close the connection
  345. // so one of the subsequent reads should return -1 signaling that the client
  346. // has effectively closed the connection
  347. }
  348. var version = SocketAbstraction.ReadByte(socket, timeout);
  349. if (version == -1)
  350. {
  351. // SOCKS client closed connection
  352. return false;
  353. }
  354. if (version != 5)
  355. throw new ProxyException("SOCKS5: Version 5 is expected.");
  356. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  357. if (commandCode == -1)
  358. {
  359. // SOCKS client closed connection
  360. return false;
  361. }
  362. var reserved = SocketAbstraction.ReadByte(socket, timeout);
  363. if (reserved == -1)
  364. {
  365. // SOCKS client closed connection
  366. return false;
  367. }
  368. if (reserved != 0)
  369. {
  370. throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
  371. }
  372. var addressType = SocketAbstraction.ReadByte(socket, timeout);
  373. if (addressType == -1)
  374. {
  375. // SOCKS client closed connection
  376. return false;
  377. }
  378. IPAddress ipAddress;
  379. byte[] addressBuffer;
  380. switch (addressType)
  381. {
  382. case 0x01:
  383. {
  384. addressBuffer = new byte[4];
  385. if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0)
  386. {
  387. // SOCKS client closed connection
  388. return false;
  389. }
  390. ipAddress = new IPAddress(addressBuffer);
  391. }
  392. break;
  393. case 0x03:
  394. {
  395. var length = SocketAbstraction.ReadByte(socket, timeout);
  396. if (length == -1)
  397. {
  398. // SOCKS client closed connection
  399. return false;
  400. }
  401. addressBuffer = new byte[length];
  402. if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0)
  403. {
  404. // SOCKS client closed connection
  405. return false;
  406. }
  407. ipAddress = IPAddress.Parse(SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length));
  408. //var hostName = new Common.ASCIIEncoding().GetString(addressBuffer);
  409. //ipAddress = Dns.GetHostEntry(hostName).AddressList[0];
  410. }
  411. break;
  412. case 0x04:
  413. {
  414. addressBuffer = new byte[16];
  415. if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0)
  416. {
  417. // SOCKS client closed connection
  418. return false;
  419. }
  420. ipAddress = new IPAddress(addressBuffer);
  421. }
  422. break;
  423. default:
  424. throw new ProxyException(string.Format("SOCKS5: Address type '{0}' is not supported.", addressType));
  425. }
  426. var portBuffer = new byte[2];
  427. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  428. {
  429. // SOCKS client closed connection
  430. return false;
  431. }
  432. var port = (uint)(portBuffer[0] * 256 + portBuffer[1]);
  433. var host = ipAddress.ToString();
  434. RaiseRequestReceived(host, port);
  435. channel.Open(host, port, this, socket);
  436. SocketAbstraction.SendByte(socket, 0x05);
  437. if (channel.IsOpen)
  438. {
  439. SocketAbstraction.SendByte(socket, 0x00);
  440. }
  441. else
  442. {
  443. SocketAbstraction.SendByte(socket, 0x01);
  444. }
  445. // reserved
  446. SocketAbstraction.SendByte(socket, 0x00);
  447. if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
  448. {
  449. SocketAbstraction.SendByte(socket, 0x01);
  450. }
  451. else if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  452. {
  453. SocketAbstraction.SendByte(socket, 0x04);
  454. }
  455. else
  456. {
  457. throw new NotSupportedException("Not supported address family.");
  458. }
  459. var addressBytes = ipAddress.GetAddressBytes();
  460. SocketAbstraction.Send(socket, addressBytes, 0, addressBytes.Length);
  461. SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
  462. return true;
  463. }
  464. /// <summary>
  465. /// Reads a null terminated string from a socket.
  466. /// </summary>
  467. /// <param name="socket">The <see cref="Socket"/> to read from.</param>
  468. /// <param name="timeout">The timeout to apply to individual reads.</param>
  469. /// <returns>
  470. /// The <see cref="string"/> read, or <c>null</c> when the socket was closed.
  471. /// </returns>
  472. private static string ReadString(Socket socket, TimeSpan timeout)
  473. {
  474. var text = new StringBuilder();
  475. var buffer = new byte[1];
  476. while (true)
  477. {
  478. if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0)
  479. {
  480. // SOCKS client closed connection
  481. return null;
  482. }
  483. var byteRead = buffer[0];
  484. if (byteRead == 0)
  485. {
  486. // end of the string
  487. break;
  488. }
  489. var c = (char) byteRead;
  490. text.Append(c);
  491. }
  492. return text.ToString();
  493. }
  494. }
  495. }