ForwardedPortDynamic.NET.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. if (!_pendingChannelCountdown.Wait(timeout))
  237. {
  238. // TODO: log as warning
  239. DiagnosticAbstraction.Log("Timeout waiting for pending channels in dynamic forwarded port to close.");
  240. }
  241. }
  242. partial void InternalDispose(bool disposing)
  243. {
  244. if (disposing)
  245. {
  246. var listener = _listener;
  247. if (listener != null)
  248. {
  249. _listener = null;
  250. listener.Dispose();
  251. }
  252. var pendingRequestsCountdown = _pendingChannelCountdown;
  253. if (pendingRequestsCountdown != null)
  254. {
  255. _pendingChannelCountdown = null;
  256. pendingRequestsCountdown.Dispose();
  257. }
  258. }
  259. }
  260. private void Session_Disconnected(object sender, EventArgs e)
  261. {
  262. var session = Session;
  263. if (session != null)
  264. {
  265. StopPort(session.ConnectionInfo.Timeout);
  266. }
  267. }
  268. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  269. {
  270. var session = Session;
  271. if (session != null)
  272. {
  273. StopPort(session.ConnectionInfo.Timeout);
  274. }
  275. }
  276. private void Channel_Exception(object sender, ExceptionEventArgs e)
  277. {
  278. RaiseExceptionEvent(e.Exception);
  279. }
  280. private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  281. {
  282. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  283. if (commandCode == -1)
  284. {
  285. // SOCKS client closed connection
  286. return false;
  287. }
  288. // TODO: See what need to be done depends on the code
  289. var portBuffer = new byte[2];
  290. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  291. {
  292. // SOCKS client closed connection
  293. return false;
  294. }
  295. var port = Pack.BigEndianToUInt16(portBuffer);
  296. var ipBuffer = new byte[4];
  297. if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0)
  298. {
  299. // SOCKS client closed connection
  300. return false;
  301. }
  302. var ipAddress = new IPAddress(ipBuffer);
  303. var username = ReadString(socket, timeout);
  304. if (username == null)
  305. {
  306. // SOCKS client closed connection
  307. return false;
  308. }
  309. var host = ipAddress.ToString();
  310. RaiseRequestReceived(host, port);
  311. channel.Open(host, port, this, socket);
  312. SocketAbstraction.SendByte(socket, 0x00);
  313. if (channel.IsOpen)
  314. {
  315. SocketAbstraction.SendByte(socket, 0x5a);
  316. SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
  317. SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length);
  318. return true;
  319. }
  320. // signal that request was rejected or failed
  321. SocketAbstraction.SendByte(socket, 0x5b);
  322. return false;
  323. }
  324. private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
  325. {
  326. var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout);
  327. if (authenticationMethodsCount == -1)
  328. {
  329. // SOCKS client closed connection
  330. return false;
  331. }
  332. var authenticationMethods = new byte[authenticationMethodsCount];
  333. if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0)
  334. {
  335. // SOCKS client closed connection
  336. return false;
  337. }
  338. if (authenticationMethods.Min() == 0)
  339. {
  340. // no user authentication is one of the authentication methods supported
  341. // by the SOCKS client
  342. SocketAbstraction.Send(socket, new byte[] {0x05, 0x00}, 0, 2);
  343. }
  344. else
  345. {
  346. // the SOCKS client requires authentication, which we currently do not support
  347. SocketAbstraction.Send(socket, new byte[] {0x05, 0xFF}, 0, 2);
  348. // we continue business as usual but expect the client to close the connection
  349. // so one of the subsequent reads should return -1 signaling that the client
  350. // has effectively closed the connection
  351. }
  352. var version = SocketAbstraction.ReadByte(socket, timeout);
  353. if (version == -1)
  354. {
  355. // SOCKS client closed connection
  356. return false;
  357. }
  358. if (version != 5)
  359. throw new ProxyException("SOCKS5: Version 5 is expected.");
  360. var commandCode = SocketAbstraction.ReadByte(socket, timeout);
  361. if (commandCode == -1)
  362. {
  363. // SOCKS client closed connection
  364. return false;
  365. }
  366. var reserved = SocketAbstraction.ReadByte(socket, timeout);
  367. if (reserved == -1)
  368. {
  369. // SOCKS client closed connection
  370. return false;
  371. }
  372. if (reserved != 0)
  373. {
  374. throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
  375. }
  376. var addressType = SocketAbstraction.ReadByte(socket, timeout);
  377. if (addressType == -1)
  378. {
  379. // SOCKS client closed connection
  380. return false;
  381. }
  382. var host = GetSocks5Host(addressType, socket, timeout);
  383. if (host == null)
  384. {
  385. // SOCKS client closed connection
  386. return false;
  387. }
  388. var portBuffer = new byte[2];
  389. if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
  390. {
  391. // SOCKS client closed connection
  392. return false;
  393. }
  394. var port = Pack.BigEndianToUInt16(portBuffer);
  395. RaiseRequestReceived(host, port);
  396. channel.Open(host, port, this, socket);
  397. var socksReply = CreateSocks5Reply(channel.IsOpen);
  398. SocketAbstraction.Send(socket, socksReply, 0, socksReply.Length);
  399. return true;
  400. }
  401. private static string GetSocks5Host(int addressType, Socket socket, TimeSpan timeout)
  402. {
  403. switch (addressType)
  404. {
  405. case 0x01: // IPv4
  406. {
  407. var addressBuffer = new byte[4];
  408. if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0)
  409. {
  410. // SOCKS client closed connection
  411. return null;
  412. }
  413. var ipv4 = new IPAddress(addressBuffer);
  414. return ipv4.ToString();
  415. }
  416. case 0x03: // Domain name
  417. {
  418. var length = SocketAbstraction.ReadByte(socket, timeout);
  419. if (length == -1)
  420. {
  421. // SOCKS client closed connection
  422. return null;
  423. }
  424. var addressBuffer = new byte[length];
  425. if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0)
  426. {
  427. // SOCKS client closed connection
  428. return null;
  429. }
  430. var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length);
  431. return hostName;
  432. }
  433. case 0x04: // IPv6
  434. {
  435. var addressBuffer = new byte[16];
  436. if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0)
  437. {
  438. // SOCKS client closed connection
  439. return null;
  440. }
  441. var ipv6 = new IPAddress(addressBuffer);
  442. return ipv6.ToString();
  443. }
  444. default:
  445. throw new ProxyException(string.Format("SOCKS5: Address type '{0}' is not supported.", addressType));
  446. }
  447. }
  448. private static byte[] CreateSocks5Reply(bool channelOpen)
  449. {
  450. var socksReply = new byte
  451. [
  452. // SOCKS version
  453. 1 +
  454. // Reply field
  455. 1 +
  456. // Reserved; fixed: 0x00
  457. 1 +
  458. // Address type; fixed: 0x01
  459. 1 +
  460. // IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00}
  461. 4 +
  462. // server bound port; fixed: {0x00, 0x00}
  463. 2
  464. ];
  465. socksReply[0] = 0x05;
  466. if (channelOpen)
  467. {
  468. socksReply[1] = 0x00; // succeeded
  469. }
  470. else
  471. {
  472. socksReply[1] = 0x01; // general SOCKS server failure
  473. }
  474. // reserved
  475. socksReply[2] = 0x00;
  476. // IPv4 address type
  477. socksReply[3] = 0x01;
  478. return socksReply;
  479. }
  480. /// <summary>
  481. /// Reads a null terminated string from a socket.
  482. /// </summary>
  483. /// <param name="socket">The <see cref="Socket"/> to read from.</param>
  484. /// <param name="timeout">The timeout to apply to individual reads.</param>
  485. /// <returns>
  486. /// The <see cref="string"/> read, or <c>null</c> when the socket was closed.
  487. /// </returns>
  488. private static string ReadString(Socket socket, TimeSpan timeout)
  489. {
  490. var text = new StringBuilder();
  491. var buffer = new byte[1];
  492. while (true)
  493. {
  494. if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0)
  495. {
  496. // SOCKS client closed connection
  497. return null;
  498. }
  499. var byteRead = buffer[0];
  500. if (byteRead == 0)
  501. {
  502. // end of the string
  503. break;
  504. }
  505. var c = (char) byteRead;
  506. text.Append(c);
  507. }
  508. return text.ToString();
  509. }
  510. }
  511. }