ForwardedPortDynamicTest_Dispose_PortStarted_ChannelBound.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using Microsoft.VisualStudio.TestTools.UnitTesting;
  10. using Moq;
  11. using Renci.SshNet.Abstractions;
  12. using Renci.SshNet.Channels;
  13. using Renci.SshNet.Common;
  14. using Renci.SshNet.Tests.Common;
  15. namespace Renci.SshNet.Tests.Classes
  16. {
  17. [TestClass]
  18. public class ForwardedPortDynamicTest_Dispose_PortStarted_ChannelBound
  19. {
  20. private Mock<ISession> _sessionMock;
  21. private Mock<IConnectionInfo> _connectionInfoMock;
  22. private Mock<IChannelDirectTcpip> _channelMock;
  23. private ForwardedPortDynamic _forwardedPort;
  24. private IList<EventArgs> _closingRegister;
  25. private IList<ExceptionEventArgs> _exceptionRegister;
  26. private IPEndPoint _endpoint;
  27. private Socket _client;
  28. private IPEndPoint _remoteEndpoint;
  29. private string _userName;
  30. private TimeSpan _bindSleepTime;
  31. private ManualResetEvent _channelBindStarted;
  32. private ManualResetEvent _channelBindCompleted;
  33. [TestInitialize]
  34. public void Setup()
  35. {
  36. Arrange();
  37. Act();
  38. }
  39. [TestCleanup]
  40. public void Cleanup()
  41. {
  42. if (_client != null)
  43. {
  44. _client.Dispose();
  45. _client = null;
  46. }
  47. if (_forwardedPort != null)
  48. {
  49. _forwardedPort.Dispose();
  50. _forwardedPort = null;
  51. }
  52. if (_channelBindStarted != null)
  53. {
  54. _channelBindStarted.Dispose();
  55. _channelBindStarted = null;
  56. }
  57. if (_channelBindCompleted != null)
  58. {
  59. _channelBindCompleted.Dispose();
  60. _channelBindCompleted = null;
  61. }
  62. }
  63. private void CreateMocks()
  64. {
  65. _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);
  66. _sessionMock = new Mock<ISession>(MockBehavior.Strict);
  67. _channelMock = new Mock<IChannelDirectTcpip>(MockBehavior.Strict);
  68. }
  69. private void SetupData()
  70. {
  71. var random = new Random();
  72. _closingRegister = new List<EventArgs>();
  73. _exceptionRegister = new List<ExceptionEventArgs>();
  74. _endpoint = new IPEndPoint(IPAddress.Loopback, 8122);
  75. _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));
  76. _bindSleepTime = TimeSpan.FromMilliseconds(random.Next(100, 500));
  77. _userName = random.Next().ToString(CultureInfo.InvariantCulture);
  78. _channelBindStarted = new ManualResetEvent(false);
  79. _channelBindCompleted = new ManualResetEvent(false);
  80. _forwardedPort = new ForwardedPortDynamic(_endpoint.Address.ToString(), (uint)_endpoint.Port);
  81. _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
  82. _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
  83. _forwardedPort.Session = _sessionMock.Object;
  84. _client = new Socket(_endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
  85. {
  86. ReceiveTimeout = 100,
  87. SendTimeout = 100,
  88. SendBufferSize = 0
  89. };
  90. }
  91. private void SetupMocks()
  92. {
  93. _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
  94. _sessionMock.Setup(p => p.IsConnected).Returns(true);
  95. _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
  96. _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object);
  97. _channelMock.Setup(p => p.Open(_remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port, _forwardedPort, It.IsAny<Socket>()));
  98. _channelMock.Setup(p => p.IsOpen).Returns(true);
  99. _channelMock.Setup(p => p.Bind()).Callback(() =>
  100. {
  101. _channelBindStarted.Set();
  102. Thread.Sleep(_bindSleepTime);
  103. _channelBindCompleted.Set();
  104. });
  105. _channelMock.Setup(p => p.Dispose());
  106. }
  107. protected void Arrange()
  108. {
  109. CreateMocks();
  110. SetupData();
  111. SetupMocks();
  112. _forwardedPort.Start();
  113. EstablishSocks4Connection(_client);
  114. }
  115. protected void Act()
  116. {
  117. _forwardedPort.Dispose();
  118. }
  119. [TestMethod]
  120. public void ShouldBlockUntilBindHasCompleted()
  121. {
  122. Assert.IsTrue(_channelBindCompleted.WaitOne(0));
  123. }
  124. [TestMethod]
  125. public void IsStartedShouldReturnFalse()
  126. {
  127. Assert.IsFalse(_forwardedPort.IsStarted);
  128. }
  129. [TestMethod]
  130. public void ForwardedPortShouldRefuseNewConnections()
  131. {
  132. using (var client = new Socket(_endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
  133. {
  134. try
  135. {
  136. client.Connect(_endpoint);
  137. Assert.Fail();
  138. }
  139. catch (SocketException ex)
  140. {
  141. Assert.AreEqual(SocketError.ConnectionRefused, ex.SocketErrorCode);
  142. }
  143. }
  144. }
  145. [TestMethod]
  146. public void BoundClientShouldNotBeClosed()
  147. {
  148. // the forwarded port itself does not close the client connection; when the channel is closed properly
  149. // it's the channel that will take care of closing the client connection
  150. //
  151. // we'll check if the client connection is still alive by attempting to receive, which should time out
  152. // as the forwarded port (or its channel) are not sending anything
  153. var buffer = new byte[1];
  154. try
  155. {
  156. _client.Receive(buffer);
  157. Assert.Fail();
  158. }
  159. catch (SocketException ex)
  160. {
  161. Assert.AreEqual(SocketError.TimedOut, ex.SocketErrorCode);
  162. }
  163. }
  164. [TestMethod]
  165. public void ClosingShouldHaveFiredOnce()
  166. {
  167. Assert.AreEqual(1, _closingRegister.Count);
  168. }
  169. [TestMethod]
  170. public void ExceptionShouldNotHaveFired()
  171. {
  172. Assert.AreEqual(0, _exceptionRegister.Count, _exceptionRegister.AsString());
  173. }
  174. [TestMethod]
  175. public void OpenOnChannelShouldBeInvokedOnce()
  176. {
  177. _channelMock.Verify(
  178. p =>
  179. p.Open(_remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port, _forwardedPort,
  180. It.IsAny<Socket>()), Times.Once);
  181. }
  182. [TestMethod]
  183. public void BindOnChannelShouldBeInvokedOnce()
  184. {
  185. _channelMock.Verify(p => p.Bind(), Times.Once);
  186. }
  187. [TestMethod]
  188. public void DisposeOnChannelShouldBeInvokedOnce()
  189. {
  190. _channelMock.Verify(p => p.Dispose(), Times.Once);
  191. }
  192. private void EstablishSocks4Connection(Socket client)
  193. {
  194. var userNameBytes = Encoding.ASCII.GetBytes(_userName);
  195. var addressBytes = _remoteEndpoint.Address.GetAddressBytes();
  196. var portBytes = BitConverter.GetBytes((ushort)_remoteEndpoint.Port).Reverse().ToArray();
  197. _client.Connect(_endpoint);
  198. // send SOCKS version
  199. client.Send(new byte[] { 0x04 }, 0, 1, SocketFlags.None);
  200. // send command byte
  201. client.Send(new byte[] { 0x00 }, 0, 1, SocketFlags.None);
  202. // send port
  203. client.Send(portBytes, 0, portBytes.Length, SocketFlags.None);
  204. // send address
  205. client.Send(addressBytes, 0, addressBytes.Length, SocketFlags.None);
  206. // send user name
  207. client.Send(userNameBytes, 0, userNameBytes.Length, SocketFlags.None);
  208. // terminate user name with null
  209. client.Send(new byte[] { 0x00 }, 0, 1, SocketFlags.None);
  210. var buffer = new byte[8];
  211. var bytesRead = SocketAbstraction.Read(client, buffer, 0, buffer.Length, TimeSpan.FromMilliseconds(500));
  212. Assert.AreEqual(buffer.Length, bytesRead);
  213. // wait until SOCKS client is bound to channel
  214. Assert.IsTrue(_channelBindStarted.WaitOne(TimeSpan.FromMilliseconds(200)));
  215. }
  216. }
  217. }