ConnectivityTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 SftpClient_HandleSftpSessionClose()
  254. {
  255. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  256. {
  257. client.Connect();
  258. Assert.IsTrue(client.IsConnected);
  259. client.SftpSession.Disconnect();
  260. Assert.IsFalse(client.IsConnected);
  261. client.Connect();
  262. Assert.IsTrue(client.IsConnected);
  263. client.Disconnect();
  264. Assert.IsFalse(client.IsConnected);
  265. }
  266. }
  267. [TestMethod]
  268. public async Task SftpClient_HandleSftpSessionCloseAsync()
  269. {
  270. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  271. {
  272. await client.ConnectAsync(CancellationToken.None);
  273. Assert.IsTrue(client.IsConnected);
  274. client.SftpSession.Disconnect();
  275. Assert.IsFalse(client.IsConnected);
  276. await client.ConnectAsync(CancellationToken.None);
  277. Assert.IsTrue(client.IsConnected);
  278. client.Disconnect();
  279. Assert.IsFalse(client.IsConnected);
  280. }
  281. }
  282. [TestMethod]
  283. public void Common_DetectSessionKilledOnServer()
  284. {
  285. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  286. {
  287. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  288. Exception errorOccurred = null;
  289. client.ErrorOccurred += (sender, args) =>
  290. {
  291. errorOccurred = args.Exception;
  292. errorOccurredSignaled.Set();
  293. };
  294. client.Connect();
  295. // Kill the server session
  296. using (var adminClient = new SshClient(_adminConnectionInfoFactory.Create()))
  297. {
  298. adminClient.Connect();
  299. var command = $"sudo ps --no-headers -u {client.ConnectionInfo.Username} -f | grep \"{client.ConnectionInfo.Username}@notty\" | awk '{{print $2}}' | xargs sudo kill -9";
  300. var sshCommand = adminClient.CreateCommand(command);
  301. var result = sshCommand.Execute();
  302. Assert.AreEqual(0, sshCommand.ExitStatus, sshCommand.Error);
  303. }
  304. Assert.IsTrue(errorOccurredSignaled.WaitOne(200));
  305. Assert.IsNotNull(errorOccurred);
  306. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  307. Assert.IsNull(errorOccurred.InnerException);
  308. Assert.AreEqual("An established connection was aborted by the server.", errorOccurred.Message);
  309. Assert.IsFalse(client.IsConnected);
  310. }
  311. }
  312. [TestMethod]
  313. public void Common_HostKeyValidation_Failure()
  314. {
  315. using (var client = new SshClient(_connectionInfoFactory.Create()))
  316. {
  317. client.HostKeyReceived += (sender, e) => { e.CanTrust = false; };
  318. try
  319. {
  320. client.Connect();
  321. Assert.Fail();
  322. }
  323. catch (SshConnectionException ex)
  324. {
  325. Assert.IsNull(ex.InnerException);
  326. Assert.AreEqual("Key exchange negotiation failed.", ex.Message);
  327. }
  328. }
  329. }
  330. [TestMethod]
  331. public void Common_HostKeyValidation_Success()
  332. {
  333. byte[] host_rsa_key_openssh_fingerprint =
  334. {
  335. 0x3d, 0x90, 0xd8, 0x0d, 0xd5, 0xe0, 0xb6, 0x13,
  336. 0x42, 0x7c, 0x78, 0x1e, 0x19, 0xa3, 0x99, 0x2b
  337. };
  338. var hostValidationSuccessful = false;
  339. using (var client = new SshClient(_connectionInfoFactory.Create()))
  340. {
  341. client.HostKeyReceived += (sender, e) =>
  342. {
  343. if (host_rsa_key_openssh_fingerprint.Length == e.FingerPrint.Length)
  344. {
  345. for (var i = 0; i < host_rsa_key_openssh_fingerprint.Length; i++)
  346. {
  347. if (host_rsa_key_openssh_fingerprint[i] != e.FingerPrint[i])
  348. {
  349. e.CanTrust = false;
  350. break;
  351. }
  352. }
  353. hostValidationSuccessful = e.CanTrust;
  354. }
  355. else
  356. {
  357. e.CanTrust = false;
  358. }
  359. };
  360. client.Connect();
  361. }
  362. Assert.IsTrue(hostValidationSuccessful);
  363. }
  364. [TestMethod]
  365. public void Common_HostKeyValidationSHA256_Success()
  366. {
  367. var hostValidationSuccessful = false;
  368. using (var client = new SshClient(_connectionInfoFactory.Create()))
  369. {
  370. client.HostKeyReceived += (sender, e) =>
  371. {
  372. if (e.FingerPrintSHA256 == "9fa6vbz64gimzsGZ/xZi3aaYE1o7E96iU2NjcfQNGwI")
  373. {
  374. hostValidationSuccessful = e.CanTrust;
  375. }
  376. else
  377. {
  378. e.CanTrust = false;
  379. }
  380. };
  381. client.Connect();
  382. }
  383. Assert.IsTrue(hostValidationSuccessful);
  384. }
  385. [TestMethod]
  386. public void Common_HostKeyValidationMD5_Success()
  387. {
  388. var hostValidationSuccessful = false;
  389. using (var client = new SshClient(_connectionInfoFactory.Create()))
  390. {
  391. client.HostKeyReceived += (sender, e) =>
  392. {
  393. if (e.FingerPrintMD5 == "3d:90:d8:0d:d5:e0:b6:13:42:7c:78:1e:19:a3:99:2b")
  394. {
  395. hostValidationSuccessful = e.CanTrust;
  396. }
  397. else
  398. {
  399. e.CanTrust = false;
  400. }
  401. };
  402. client.Connect();
  403. }
  404. Assert.IsTrue(hostValidationSuccessful);
  405. }
  406. /// <summary>
  407. /// Verifies whether we handle a disconnect initiated by the SSH server (through a SSH_MSG_DISCONNECT message).
  408. /// </summary>
  409. /// <remarks>
  410. /// We force this by only configuring <c>keyboard-interactive</c> as authentication method, while <c>ChallengeResponseAuthentication</c>
  411. /// is not enabled. This causes OpenSSH to terminate the connection because there are no authentication methods left.
  412. /// </remarks>
  413. [TestMethod]
  414. public void Common_ServerRejectsConnection()
  415. {
  416. _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
  417. .Update()
  418. .Restart();
  419. var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserKeyboardInteractiveAuthenticationMethod());
  420. using (var client = new SftpClient(connectionInfo))
  421. {
  422. try
  423. {
  424. client.Connect();
  425. Assert.Fail();
  426. }
  427. catch (SshConnectionException ex)
  428. {
  429. Assert.AreEqual(DisconnectReason.ProtocolError, ex.DisconnectReason);
  430. Assert.IsNull(ex.InnerException);
  431. Assert.AreEqual("The connection was closed by the server: no authentication methods enabled (ProtocolError).", ex.Message);
  432. }
  433. }
  434. }
  435. }
  436. }