ForwardedPortDynamicTest_SessionErrorOccurred_ChannelBound.cs 8.9 KB

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