ConnectivityTests.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. WaitForConnectionInterruption(client);
  153. client.ListDirectory("/");
  154. Assert.Fail();
  155. }
  156. catch (SshConnectionException ex)
  157. {
  158. Assert.IsNull(ex.InnerException);
  159. Assert.AreEqual("Client not connected.", ex.Message);
  160. Assert.IsNotNull(errorOccurred);
  161. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  162. var connectionException = (SshConnectionException)errorOccurred;
  163. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  164. Assert.IsNull(connectionException.InnerException);
  165. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  166. }
  167. finally
  168. {
  169. disruptor.RestoreConnections();
  170. disruptor.Dispose();
  171. }
  172. }
  173. }
  174. [TestMethod]
  175. public void Common_LossOfNetworkConnectivityDisconnectAndConnect()
  176. {
  177. bool vmNetworkConnectionDisabled = false;
  178. SshConnectionRestorer disruptor = null;
  179. try
  180. {
  181. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  182. {
  183. Exception errorOccurred = null;
  184. client.ErrorOccurred += (sender, args) => errorOccurred = args.Exception;
  185. client.Connect();
  186. disruptor = _sshConnectionDisruptor.BreakConnections();
  187. vmNetworkConnectionDisabled = true;
  188. WaitForConnectionInterruption(client);
  189. // disconnect while network connectivity is lost
  190. client.Disconnect();
  191. Assert.IsFalse(client.IsConnected);
  192. disruptor.RestoreConnections();
  193. vmNetworkConnectionDisabled = false;
  194. // connect when network connectivity is restored
  195. client.Connect();
  196. client.ChangeDirectory(client.WorkingDirectory);
  197. client.Dispose();
  198. Assert.IsNotNull(errorOccurred);
  199. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  200. var connectionException = (SshConnectionException)errorOccurred;
  201. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  202. Assert.IsNull(connectionException.InnerException);
  203. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  204. }
  205. }
  206. finally
  207. {
  208. if (vmNetworkConnectionDisabled)
  209. {
  210. disruptor.RestoreConnections();
  211. }
  212. disruptor?.Dispose();
  213. }
  214. }
  215. [TestMethod]
  216. public void Common_DetectLossOfNetworkConnectivityThroughSftpInvocation()
  217. {
  218. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  219. {
  220. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  221. Exception errorOccurred = null;
  222. client.ErrorOccurred += (sender, args) =>
  223. {
  224. errorOccurred = args.Exception;
  225. errorOccurredSignaled.Set();
  226. };
  227. client.Connect();
  228. var disruptor = _sshConnectionDisruptor.BreakConnections();
  229. try
  230. {
  231. WaitForConnectionInterruption(client);
  232. client.ListDirectory("/");
  233. Assert.Fail();
  234. }
  235. catch (SshConnectionException ex)
  236. {
  237. Assert.IsNull(ex.InnerException);
  238. Assert.AreEqual("Client not connected.", ex.Message);
  239. Assert.IsNotNull(errorOccurred);
  240. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  241. var connectionException = (SshConnectionException)errorOccurred;
  242. Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
  243. Assert.IsNull(connectionException.InnerException);
  244. Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
  245. }
  246. finally
  247. {
  248. disruptor.RestoreConnections();
  249. disruptor.Dispose();
  250. }
  251. }
  252. }
  253. [TestMethod]
  254. public void SftpClient_HandleSftpSessionClose()
  255. {
  256. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  257. {
  258. client.Connect();
  259. Assert.IsTrue(client.IsConnected);
  260. client.SftpSession.Disconnect();
  261. Assert.IsFalse(client.IsConnected);
  262. client.Connect();
  263. Assert.IsTrue(client.IsConnected);
  264. client.Disconnect();
  265. Assert.IsFalse(client.IsConnected);
  266. }
  267. }
  268. [TestMethod]
  269. public async Task SftpClient_HandleSftpSessionCloseAsync()
  270. {
  271. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  272. {
  273. await client.ConnectAsync(CancellationToken.None);
  274. Assert.IsTrue(client.IsConnected);
  275. client.SftpSession.Disconnect();
  276. Assert.IsFalse(client.IsConnected);
  277. await client.ConnectAsync(CancellationToken.None);
  278. Assert.IsTrue(client.IsConnected);
  279. client.Disconnect();
  280. Assert.IsFalse(client.IsConnected);
  281. }
  282. }
  283. [TestMethod]
  284. public void SftpClient_HandleSftpSessionAbortByServer()
  285. {
  286. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  287. {
  288. client.Connect();
  289. Assert.IsTrue(client.IsConnected);
  290. _sshConnectionDisruptor.BreakConnections();
  291. WaitForConnectionInterruption(client);
  292. Assert.IsFalse(client.IsConnected);
  293. client.Connect();
  294. Assert.IsTrue(client.IsConnected);
  295. foreach (var file in client.ListDirectory("."))
  296. {
  297. }
  298. client.Disconnect();
  299. Assert.IsFalse(client.IsConnected);
  300. }
  301. }
  302. [TestMethod]
  303. public async Task SftpClient_HandleSftpSessionAbortByServerAsync()
  304. {
  305. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  306. {
  307. await client.ConnectAsync(CancellationToken.None);
  308. Assert.IsTrue(client.IsConnected);
  309. _sshConnectionDisruptor.BreakConnections();
  310. WaitForConnectionInterruption(client);
  311. Assert.IsFalse(client.IsConnected);
  312. await client.ConnectAsync(CancellationToken.None);
  313. Assert.IsTrue(client.IsConnected);
  314. await foreach (var file in client.ListDirectoryAsync(".", CancellationToken.None))
  315. {
  316. }
  317. client.Disconnect();
  318. Assert.IsFalse(client.IsConnected);
  319. }
  320. }
  321. [TestMethod]
  322. public void Common_DetectSessionKilledOnServer()
  323. {
  324. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  325. {
  326. ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
  327. Exception errorOccurred = null;
  328. client.ErrorOccurred += (sender, args) =>
  329. {
  330. errorOccurred = args.Exception;
  331. errorOccurredSignaled.Set();
  332. };
  333. client.Connect();
  334. // Kill the server session
  335. using (var adminClient = new SshClient(_adminConnectionInfoFactory.Create()))
  336. {
  337. adminClient.Connect();
  338. var command = $"sudo ps --no-headers -u {client.ConnectionInfo.Username} -f | grep \"{client.ConnectionInfo.Username}@notty\" | awk '{{print $2}}' | xargs sudo kill -9";
  339. var sshCommand = adminClient.CreateCommand(command);
  340. var result = sshCommand.Execute();
  341. Assert.AreEqual(0, sshCommand.ExitStatus, sshCommand.Error);
  342. }
  343. Assert.IsTrue(errorOccurredSignaled.WaitOne(200));
  344. Assert.IsNotNull(errorOccurred);
  345. Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
  346. Assert.IsNull(errorOccurred.InnerException);
  347. Assert.AreEqual("An established connection was aborted by the server.", errorOccurred.Message);
  348. Assert.IsFalse(client.IsConnected);
  349. }
  350. }
  351. [TestMethod]
  352. public void Common_HostKeyValidation_Failure()
  353. {
  354. using (var client = new SshClient(_connectionInfoFactory.Create()))
  355. {
  356. client.HostKeyReceived += (sender, e) => { e.CanTrust = false; };
  357. try
  358. {
  359. client.Connect();
  360. Assert.Fail();
  361. }
  362. catch (SshConnectionException ex)
  363. {
  364. Assert.IsNull(ex.InnerException);
  365. Assert.AreEqual("Key exchange negotiation failed.", ex.Message);
  366. }
  367. }
  368. }
  369. [TestMethod]
  370. public void Common_HostKeyValidation_Success()
  371. {
  372. byte[] host_rsa_key_openssh_fingerprint =
  373. {
  374. 0x3d, 0x90, 0xd8, 0x0d, 0xd5, 0xe0, 0xb6, 0x13,
  375. 0x42, 0x7c, 0x78, 0x1e, 0x19, 0xa3, 0x99, 0x2b
  376. };
  377. var hostValidationSuccessful = false;
  378. using (var client = new SshClient(_connectionInfoFactory.Create()))
  379. {
  380. client.HostKeyReceived += (sender, e) =>
  381. {
  382. if (host_rsa_key_openssh_fingerprint.Length == e.FingerPrint.Length)
  383. {
  384. for (var i = 0; i < host_rsa_key_openssh_fingerprint.Length; i++)
  385. {
  386. if (host_rsa_key_openssh_fingerprint[i] != e.FingerPrint[i])
  387. {
  388. e.CanTrust = false;
  389. break;
  390. }
  391. }
  392. hostValidationSuccessful = e.CanTrust;
  393. }
  394. else
  395. {
  396. e.CanTrust = false;
  397. }
  398. };
  399. client.Connect();
  400. }
  401. Assert.IsTrue(hostValidationSuccessful);
  402. }
  403. [TestMethod]
  404. public void Common_HostKeyValidationSHA256_Success()
  405. {
  406. var hostValidationSuccessful = false;
  407. using (var client = new SshClient(_connectionInfoFactory.Create()))
  408. {
  409. client.HostKeyReceived += (sender, e) =>
  410. {
  411. if (e.FingerPrintSHA256 == "9fa6vbz64gimzsGZ/xZi3aaYE1o7E96iU2NjcfQNGwI")
  412. {
  413. hostValidationSuccessful = e.CanTrust;
  414. }
  415. else
  416. {
  417. e.CanTrust = false;
  418. }
  419. };
  420. client.Connect();
  421. }
  422. Assert.IsTrue(hostValidationSuccessful);
  423. }
  424. [TestMethod]
  425. public void Common_HostKeyValidationMD5_Success()
  426. {
  427. var hostValidationSuccessful = false;
  428. using (var client = new SshClient(_connectionInfoFactory.Create()))
  429. {
  430. client.HostKeyReceived += (sender, e) =>
  431. {
  432. if (e.FingerPrintMD5 == "3d:90:d8:0d:d5:e0:b6:13:42:7c:78:1e:19:a3:99:2b")
  433. {
  434. hostValidationSuccessful = e.CanTrust;
  435. }
  436. else
  437. {
  438. e.CanTrust = false;
  439. }
  440. };
  441. client.Connect();
  442. }
  443. Assert.IsTrue(hostValidationSuccessful);
  444. }
  445. /// <summary>
  446. /// Verifies whether we handle a disconnect initiated by the SSH server (through a SSH_MSG_DISCONNECT message).
  447. /// </summary>
  448. /// <remarks>
  449. /// We force this by only configuring <c>keyboard-interactive</c> as authentication method, while <c>ChallengeResponseAuthentication</c>
  450. /// is not enabled. This causes OpenSSH to terminate the connection because there are no authentication methods left.
  451. /// </remarks>
  452. [TestMethod]
  453. public void Common_ServerRejectsConnection()
  454. {
  455. _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
  456. .Update()
  457. .Restart();
  458. var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserKeyboardInteractiveAuthenticationMethod());
  459. using (var client = new SftpClient(connectionInfo))
  460. {
  461. try
  462. {
  463. client.Connect();
  464. Assert.Fail();
  465. }
  466. catch (SshConnectionException ex)
  467. {
  468. Assert.AreEqual(DisconnectReason.ProtocolError, ex.DisconnectReason);
  469. Assert.IsNull(ex.InnerException);
  470. Assert.AreEqual("The connection was closed by the server: no authentication methods enabled (ProtocolError).", ex.Message);
  471. }
  472. }
  473. }
  474. }
  475. }