ConnectivityTests.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. using Renci.SshNet.Common;
  2. using Renci.SshNet.IntegrationTests.Common;
  3. using Renci.SshNet.Messages.Transport;
  4. namespace Renci.SshNet.IntegrationTests
  5. {
  6. [TestClass]
  7. public class ConnectivityTests : IntegrationTestBase
  8. {
  9. private AuthenticationMethodFactory _authenticationMethodFactory;
  10. private IConnectionInfoFactory _connectionInfoFactory;
  11. private IConnectionInfoFactory _adminConnectionInfoFactory;
  12. private RemoteSshdConfig _remoteSshdConfig;
  13. private SshConnectionDisruptor _sshConnectionDisruptor;
  14. [TestInitialize]
  15. public void SetUp()
  16. {
  17. _authenticationMethodFactory = new AuthenticationMethodFactory();
  18. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort, _authenticationMethodFactory);
  19. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  20. _remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  21. _sshConnectionDisruptor = new SshConnectionDisruptor(_adminConnectionInfoFactory);
  22. }
  23. [TestCleanup]
  24. public void TearDown()
  25. {
  26. _remoteSshdConfig?.Reset();
  27. }
  28. [TestMethod]
  29. public void Common_CreateMoreChannelsThanMaxSessions()
  30. {
  31. var connectionInfo = _connectionInfoFactory.Create();
  32. connectionInfo.MaxSessions = 2;
  33. using (var client = new SshClient(connectionInfo))
  34. {
  35. client.Connect();
  36. // create one more channel than the maximum number of sessions
  37. // as that would block indefinitely when creating the last channel
  38. // if the channel would not be properly closed
  39. for (var i = 0; i < connectionInfo.MaxSessions + 1; i++)
  40. {
  41. using (var stream = client.CreateShellStream("vt220", 20, 20, 20, 20, 20))
  42. {
  43. stream.WriteLine("echo test");
  44. stream.ReadLine();
  45. }
  46. }
  47. }
  48. }
  49. [TestMethod]
  50. public void Common_DisposeAfterLossOfNetworkConnectivity()
  51. {
  52. var hostNetworkConnectionDisabled = false;
  53. SshConnectionRestorer disruptor = null;
  54. try
  55. {
  56. Exception errorOccurred = null;
  57. int count = 0;
  58. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  59. {
  60. client.ErrorOccurred += (sender, args) =>
  61. {
  62. Console.WriteLine("Exception " + count++);
  63. Console.WriteLine(args.Exception);
  64. errorOccurred = args.Exception;
  65. };
  66. client.Connect();
  67. disruptor = _sshConnectionDisruptor.BreakConnections();
  68. hostNetworkConnectionDisabled = true;
  69. WaitForConnectionInterruption(client);
  70. }
  71. Assert.IsNotNull(errorOccurred);
  72. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  73. var connectionException = (SshConnectionException) errorOccurred;
  74. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  75. Assert.IsNull(connectionException.InnerException);
  76. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  77. }
  78. finally
  79. {
  80. if (hostNetworkConnectionDisabled)
  81. {
  82. disruptor?.RestoreConnections();
  83. disruptor?.Dispose();
  84. }
  85. }
  86. }
  87. [TestMethod]
  88. public void Common_DetectLossOfNetworkConnectivityThroughKeepAlive()
  89. {
  90. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  91. {
  92. Exception errorOccurred = null;
  93. int count = 0;
  94. client.ErrorOccurred += (sender, args) =>
  95. {
  96. Console.WriteLine("Exception "+ count++);
  97. Console.WriteLine(args.Exception);
  98. errorOccurred = args.Exception;
  99. };
  100. client.KeepAliveInterval = new TimeSpan(0, 0, 0, 0, 50);
  101. client.Connect();
  102. var disruptor = _sshConnectionDisruptor.BreakConnections();
  103. try
  104. {
  105. WaitForConnectionInterruption(client);
  106. Assert.IsFalse(client.IsConnected);
  107. Assert.IsNotNull(errorOccurred);
  108. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  109. var connectionException = (SshConnectionException) errorOccurred;
  110. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  111. Assert.IsNull(connectionException.InnerException);
  112. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  113. }
  114. finally
  115. {
  116. disruptor?.RestoreConnections();
  117. disruptor?.Dispose();
  118. }
  119. }
  120. }
  121. private static void WaitForConnectionInterruption(SftpClient client)
  122. {
  123. for (var i = 0; i < 500; i++)
  124. {
  125. if (!client.IsConnected)
  126. {
  127. break;
  128. }
  129. Thread.Sleep(100);
  130. }
  131. // After interruption, you have to wait for the events to propagate.
  132. Thread.Sleep(100);
  133. }
  134. [TestMethod]
  135. public void Common_DetectConnectionResetThroughSftpInvocation()
  136. {
  137. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  138. {
  139. client.KeepAliveInterval = TimeSpan.FromSeconds(1);
  140. client.OperationTimeout = TimeSpan.FromSeconds(60);
  141. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  142. Exception errorOccurred = null;
  143. client.ErrorOccurred += (sender, args) =>
  144. {
  145. errorOccurred = args.Exception;
  146. errorOccurredSignaled.Set();
  147. };
  148. client.Connect();
  149. var disruptor = _sshConnectionDisruptor.BreakConnections();
  150. try
  151. {
  152. client.ListDirectory("/");
  153. Assert.Fail();
  154. }
  155. catch (SshConnectionException ex)
  156. {
  157. Assert.IsNull(ex.InnerException);
  158. Assert.AreEqual("Client not connected.", ex.Message);
  159. Assert.IsNotNull(errorOccurred);
  160. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  161. var connectionException = (SshConnectionException) errorOccurred;
  162. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  163. Assert.IsNull(connectionException.InnerException);
  164. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  165. }
  166. finally
  167. {
  168. disruptor.RestoreConnections();
  169. disruptor.Dispose();
  170. }
  171. }
  172. }
  173. [TestMethod]
  174. public void Common_LossOfNetworkConnectivityDisconnectAndConnect()
  175. {
  176. bool vmNetworkConnectionDisabled = false;
  177. SshConnectionRestorer disruptor = null;
  178. try
  179. {
  180. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  181. {
  182. Exception errorOccurred = null;
  183. client.ErrorOccurred += (sender, args) => errorOccurred = args.Exception;
  184. client.Connect();
  185. disruptor = _sshConnectionDisruptor.BreakConnections();
  186. vmNetworkConnectionDisabled = true;
  187. WaitForConnectionInterruption(client);
  188. // disconnect while network connectivity is lost
  189. client.Disconnect();
  190. Assert.IsFalse(client.IsConnected);
  191. disruptor.RestoreConnections();
  192. vmNetworkConnectionDisabled = false;
  193. // connect when network connectivity is restored
  194. client.Connect();
  195. client.ChangeDirectory(client.WorkingDirectory);
  196. client.Dispose();
  197. Assert.IsNotNull(errorOccurred);
  198. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  199. var connectionException = (SshConnectionException) errorOccurred;
  200. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  201. Assert.IsNull(connectionException.InnerException);
  202. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  203. }
  204. }
  205. finally
  206. {
  207. if (vmNetworkConnectionDisabled)
  208. {
  209. disruptor.RestoreConnections();
  210. }
  211. disruptor?.Dispose();
  212. }
  213. }
  214. [TestMethod]
  215. public void Common_DetectLossOfNetworkConnectivityThroughSftpInvocation()
  216. {
  217. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  218. {
  219. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  220. Exception errorOccurred = null;
  221. client.ErrorOccurred += (sender, args) =>
  222. {
  223. errorOccurred = args.Exception;
  224. errorOccurredSignaled.Set();
  225. };
  226. client.Connect();
  227. var disruptor = _sshConnectionDisruptor.BreakConnections();
  228. Thread.Sleep(100);
  229. try
  230. {
  231. client.ListDirectory("/");
  232. Assert.Fail();
  233. }
  234. catch (SshConnectionException ex)
  235. {
  236. Assert.IsNull(ex.InnerException);
  237. Assert.AreEqual("Client not connected.", ex.Message);
  238. Assert.IsNotNull(errorOccurred);
  239. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  240. var connectionException = (SshConnectionException) errorOccurred;
  241. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  242. Assert.IsNull(connectionException.InnerException);
  243. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  244. }
  245. finally
  246. {
  247. disruptor.RestoreConnections();
  248. disruptor.Dispose();
  249. }
  250. }
  251. }
  252. [TestMethod]
  253. public void Common_DetectSessionKilledOnServer()
  254. {
  255. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  256. {
  257. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  258. Exception errorOccurred = null;
  259. client.ErrorOccurred += (sender, args) =>
  260. {
  261. errorOccurred = args.Exception;
  262. errorOccurredSignaled.Set();
  263. };
  264. client.Connect();
  265. // Kill the server session
  266. using (var adminClient = new SshClient(_adminConnectionInfoFactory.Create()))
  267. {
  268. adminClient.Connect();
  269. var command = $"sudo ps --no-headers -u {client.ConnectionInfo.Username} -f | grep \"{client.ConnectionInfo.Username}@notty\" | awk '{{print $2}}' | xargs sudo kill -9";
  270. var sshCommand = adminClient.CreateCommand(command);
  271. var result = sshCommand.Execute();
  272. Assert.AreEqual(0, sshCommand.ExitStatus, sshCommand.Error);
  273. }
  274. Assert.IsTrue(errorOccurredSignaled.WaitOne(200));
  275. Assert.IsNotNull(errorOccurred);
  276. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  277. Assert.IsNull(errorOccurred.InnerException);
  278. Assert.AreEqual("An established connection was aborted by the server.", errorOccurred.Message);
  279. Assert.IsFalse(client.IsConnected);
  280. }
  281. }
  282. [TestMethod]
  283. public void Common_HostKeyValidation_Failure()
  284. {
  285. using (var client = new SshClient(_connectionInfoFactory.Create()))
  286. {
  287. client.HostKeyReceived += (sender, e) => { e.CanTrust = false; };
  288. try
  289. {
  290. client.Connect();
  291. Assert.Fail();
  292. }
  293. catch (SshConnectionException ex)
  294. {
  295. Assert.IsNull(ex.InnerException);
  296. Assert.AreEqual("Key exchange negotiation failed.", ex.Message);
  297. }
  298. }
  299. }
  300. [TestMethod]
  301. public void Common_HostKeyValidation_Success()
  302. {
  303. byte[] host_rsa_key_openssh_fingerprint =
  304. {
  305. 0x3d, 0x90, 0xd8, 0x0d, 0xd5, 0xe0, 0xb6, 0x13,
  306. 0x42, 0x7c, 0x78, 0x1e, 0x19, 0xa3, 0x99, 0x2b
  307. };
  308. var hostValidationSuccessful = false;
  309. using (var client = new SshClient(_connectionInfoFactory.Create()))
  310. {
  311. client.HostKeyReceived += (sender, e) =>
  312. {
  313. if (host_rsa_key_openssh_fingerprint.Length == e.FingerPrint.Length)
  314. {
  315. for (var i = 0; i < host_rsa_key_openssh_fingerprint.Length; i++)
  316. {
  317. if (host_rsa_key_openssh_fingerprint[i] != e.FingerPrint[i])
  318. {
  319. e.CanTrust = false;
  320. break;
  321. }
  322. }
  323. hostValidationSuccessful = e.CanTrust;
  324. }
  325. else
  326. {
  327. e.CanTrust = false;
  328. }
  329. };
  330. client.Connect();
  331. }
  332. Assert.IsTrue(hostValidationSuccessful);
  333. }
  334. [TestMethod]
  335. public void Common_HostKeyValidationSHA256_Success()
  336. {
  337. var hostValidationSuccessful = false;
  338. using (var client = new SshClient(_connectionInfoFactory.Create()))
  339. {
  340. client.HostKeyReceived += (sender, e) =>
  341. {
  342. if (e.FingerPrintSHA256 == "9fa6vbz64gimzsGZ/xZi3aaYE1o7E96iU2NjcfQNGwI")
  343. {
  344. hostValidationSuccessful = e.CanTrust;
  345. }
  346. else
  347. {
  348. e.CanTrust = false;
  349. }
  350. };
  351. client.Connect();
  352. }
  353. Assert.IsTrue(hostValidationSuccessful);
  354. }
  355. [TestMethod]
  356. public void Common_HostKeyValidationMD5_Success()
  357. {
  358. var hostValidationSuccessful = false;
  359. using (var client = new SshClient(_connectionInfoFactory.Create()))
  360. {
  361. client.HostKeyReceived += (sender, e) =>
  362. {
  363. if (e.FingerPrintMD5 == "3d:90:d8:0d:d5:e0:b6:13:42:7c:78:1e:19:a3:99:2b")
  364. {
  365. hostValidationSuccessful = e.CanTrust;
  366. }
  367. else
  368. {
  369. e.CanTrust = false;
  370. }
  371. };
  372. client.Connect();
  373. }
  374. Assert.IsTrue(hostValidationSuccessful);
  375. }
  376. /// <summary>
  377. /// Verifies whether we handle a disconnect initiated by the SSH server (through a SSH_MSG_DISCONNECT message).
  378. /// </summary>
  379. /// <remarks>
  380. /// We force this by only configuring <c>keyboard-interactive</c> as authentication method, while <c>ChallengeResponseAuthentication</c>
  381. /// is not enabled. This causes OpenSSH to terminate the connection because there are no authentication methods left.
  382. /// </remarks>
  383. [TestMethod]
  384. public void Common_ServerRejectsConnection()
  385. {
  386. _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
  387. .Update()
  388. .Restart();
  389. var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserKeyboardInteractiveAuthenticationMethod());
  390. using (var client = new SftpClient(connectionInfo))
  391. {
  392. try
  393. {
  394. client.Connect();
  395. Assert.Fail();
  396. }
  397. catch (SshConnectionException ex)
  398. {
  399. Assert.AreEqual(DisconnectReason.ProtocolError, ex.DisconnectReason);
  400. Assert.IsNull(ex.InnerException);
  401. Assert.AreEqual("The connection was closed by the server: no authentication methods enabled (ProtocolError).", ex.Message);
  402. }
  403. }
  404. }
  405. }
  406. }