ForwardedPortDynamicTest_Stop_PortStarted_ChannelBound.cs 8.0 KB

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