SshTests.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. using System.ComponentModel;
  2. using System.Net;
  3. #if NETFRAMEWORK
  4. using System.Net.Http;
  5. #endif
  6. using System.Net.Sockets;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.IntegrationTests.Common;
  9. using Renci.SshNet.Tests.Common;
  10. namespace Renci.SshNet.IntegrationTests
  11. {
  12. [TestClass]
  13. public class SshTests : TestBase
  14. {
  15. private IConnectionInfoFactory _connectionInfoFactory;
  16. private IConnectionInfoFactory _adminConnectionInfoFactory;
  17. private RemoteSshdConfig _remoteSshdConfig;
  18. [TestInitialize]
  19. public void SetUp()
  20. {
  21. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  22. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  23. _remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  24. _remoteSshdConfig.AllowTcpForwarding()
  25. .PermitTTY(true)
  26. .PrintMotd(false)
  27. .Update()
  28. .Restart();
  29. }
  30. [TestCleanup]
  31. public void TearDown()
  32. {
  33. _remoteSshdConfig?.Reset();
  34. }
  35. /// <summary>
  36. /// Test for a channel that is being closed by the server.
  37. /// </summary>
  38. [TestMethod]
  39. public void Ssh_ShellStream_Exit()
  40. {
  41. using (var client = new SshClient(_connectionInfoFactory.Create()))
  42. {
  43. client.Connect();
  44. var terminalModes = new Dictionary<TerminalModes, uint>
  45. {
  46. { TerminalModes.ECHO, 0 }
  47. };
  48. using (var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, terminalModes))
  49. {
  50. shellStream.WriteLine("echo Hello!");
  51. shellStream.WriteLine("exit");
  52. Thread.Sleep(1000);
  53. try
  54. {
  55. shellStream.Write("ABC");
  56. Assert.Fail();
  57. }
  58. catch (ObjectDisposedException ex)
  59. {
  60. Assert.IsNull(ex.InnerException);
  61. Assert.AreEqual("Renci.SshNet.ShellStream", ex.ObjectName);
  62. Assert.AreEqual($"Cannot access a disposed object.{Environment.NewLine}Object name: '{ex.ObjectName}'.", ex.Message);
  63. }
  64. var line = shellStream.ReadLine();
  65. Assert.IsNotNull(line);
  66. Assert.IsTrue(line.EndsWith("Hello!"), line);
  67. Assert.IsTrue(shellStream.ReadLine() is null || shellStream.ReadLine() is null); // we might first get e.g. "renci-ssh-tests-server:~$"
  68. }
  69. }
  70. }
  71. [TestMethod]
  72. public void Ssh_CreateShellStreamNoTerminal()
  73. {
  74. using (var client = new SshClient(_connectionInfoFactory.Create()))
  75. {
  76. client.Connect();
  77. using (var shellStream = client.CreateShellStreamNoTerminal(bufferSize: 1024))
  78. {
  79. var foo = new string('a', 90);
  80. shellStream.WriteLine($"echo {foo}");
  81. var line = shellStream.ReadLine(TimeSpan.FromSeconds(1));
  82. Assert.IsNotNull(line);
  83. Assert.IsTrue(line.EndsWith(foo), line);
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// https://github.com/sshnet/SSH.NET/issues/63
  89. /// </summary>
  90. [TestMethod]
  91. [Category("Reproduction Tests")]
  92. public void Ssh_ShellStream_IntermittendOutput()
  93. {
  94. const string remoteFile = "/home/sshnet/test.sh";
  95. List<string> expectedLines = ["renci-ssh-tests-server:~$ Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  96. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  97. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  98. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  99. "Line 5 ",
  100. "Line 6",
  101. "renci-ssh-tests-server:~$ "]; // No idea how stable this is.
  102. var scriptBuilder = new StringBuilder();
  103. scriptBuilder.Append("#!/bin/sh\n");
  104. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  105. scriptBuilder.Append("sleep .5\n");
  106. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  107. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  108. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  109. scriptBuilder.Append("sleep 2\n");
  110. scriptBuilder.Append("echo \"Line 5 \"\n");
  111. scriptBuilder.Append("echo Line 6 \n");
  112. scriptBuilder.Append("exit 13\n");
  113. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  114. {
  115. sshClient.Connect();
  116. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  117. try
  118. {
  119. var terminalModes = new Dictionary<TerminalModes, uint>
  120. {
  121. { TerminalModes.ECHO, 0 }
  122. };
  123. using (var shellStream = sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024, terminalModes))
  124. {
  125. shellStream.WriteLine(remoteFile);
  126. shellStream.WriteLine("exit");
  127. using (var reader = new StreamReader(shellStream))
  128. {
  129. var lines = new List<string>();
  130. string line = null;
  131. while ((line = reader.ReadLine()) != null)
  132. {
  133. lines.Add(line);
  134. }
  135. CollectionAssert.AreEqual(expectedLines, lines, string.Join("\n", lines));
  136. }
  137. }
  138. }
  139. finally
  140. {
  141. RemoveFileOrDirectory(sshClient, remoteFile);
  142. }
  143. }
  144. }
  145. /// <summary>
  146. /// Issue 1555
  147. /// </summary>
  148. [TestMethod]
  149. public void Ssh_CreateShell()
  150. {
  151. using (var client = new SshClient(_connectionInfoFactory.Create()))
  152. {
  153. client.Connect();
  154. using (var input = new MemoryStream())
  155. using (var output = new MemoryStream())
  156. using (var extOutput = new MemoryStream())
  157. {
  158. var shell = client.CreateShell(input, output, extOutput);
  159. shell.Start();
  160. var inputWriter = new StreamWriter(input, Encoding.ASCII, 1024);
  161. inputWriter.WriteLine("echo $PATH");
  162. var outputReader = new StreamReader(output, Encoding.ASCII, false, 1024);
  163. Console.WriteLine(outputReader.ReadToEnd());
  164. shell.Stop();
  165. }
  166. }
  167. }
  168. [TestMethod]
  169. public void Ssh_CreateShellNoTerminal()
  170. {
  171. using (var client = new SshClient(_connectionInfoFactory.Create()))
  172. {
  173. client.Connect();
  174. using (var input = new MemoryStream())
  175. using (var output = new MemoryStream())
  176. using (var extOutput = new MemoryStream())
  177. {
  178. var shell = client.CreateShellNoTerminal(input, output, extOutput, 1024);
  179. shell.Start();
  180. var inputWriter = new StreamWriter(input, Encoding.ASCII, 1024);
  181. var foo = new string('a', 90);
  182. inputWriter.WriteLine($"echo {foo}");
  183. inputWriter.Flush();
  184. input.Position = 0;
  185. Thread.Sleep(1000);
  186. output.Position = 0;
  187. var outputReader = new StreamReader(output, Encoding.ASCII, false, 1024);
  188. var outputString = outputReader.ReadLine();
  189. Assert.IsNotNull(outputString);
  190. Assert.IsTrue(outputString.EndsWith(foo), outputString);
  191. shell.Stop();
  192. }
  193. }
  194. }
  195. [TestMethod]
  196. public void Ssh_Command_IntermittentOutput_EndExecute()
  197. {
  198. const string remoteFile = "/home/sshnet/test.sh";
  199. var expectedResult = string.Join("\n",
  200. "Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  201. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  202. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  203. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  204. "Line 5 ",
  205. "Line 6",
  206. "");
  207. var scriptBuilder = new StringBuilder();
  208. scriptBuilder.Append("#!/bin/sh\n");
  209. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  210. scriptBuilder.Append("sleep .5\n");
  211. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  212. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  213. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  214. scriptBuilder.Append("sleep 2\n");
  215. scriptBuilder.Append("echo \"Line 5 \"\n");
  216. scriptBuilder.Append("echo Line 6 \n");
  217. scriptBuilder.Append("exit 13\n");
  218. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  219. {
  220. sshClient.Connect();
  221. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  222. try
  223. {
  224. using (var cmd = sshClient.CreateCommand("chmod 777 " + remoteFile))
  225. {
  226. cmd.Execute();
  227. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  228. }
  229. using (var command = sshClient.CreateCommand(remoteFile))
  230. {
  231. var asyncResult = command.BeginExecute();
  232. var actualResult = command.EndExecute(asyncResult);
  233. Assert.AreEqual(expectedResult, actualResult);
  234. Assert.AreEqual(expectedResult, command.Result);
  235. Assert.AreEqual(13, command.ExitStatus);
  236. }
  237. }
  238. finally
  239. {
  240. RemoveFileOrDirectory(sshClient, remoteFile);
  241. }
  242. }
  243. }
  244. [TestMethod]
  245. public async Task Ssh_Command_IntermittentOutput_OutputStream()
  246. {
  247. const string remoteFile = "/home/sshnet/test.sh";
  248. var expectedResult = string.Join("\n",
  249. "Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  250. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  251. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  252. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  253. "Line 5 ",
  254. "Line 6");
  255. var scriptBuilder = new StringBuilder();
  256. scriptBuilder.Append("#!/bin/sh\n");
  257. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  258. scriptBuilder.Append("sleep .5\n");
  259. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  260. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  261. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  262. scriptBuilder.Append("sleep 2\n");
  263. scriptBuilder.Append("echo \"Line 5 \"\n");
  264. scriptBuilder.Append("echo Line 6 \n");
  265. scriptBuilder.Append("exit 13\n");
  266. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  267. {
  268. sshClient.Connect();
  269. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  270. try
  271. {
  272. using (var cmd = sshClient.CreateCommand("chmod 777 " + remoteFile))
  273. {
  274. await cmd.ExecuteAsync();
  275. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  276. }
  277. using (var command = sshClient.CreateCommand(remoteFile))
  278. {
  279. await command.ExecuteAsync();
  280. Assert.AreEqual(13, command.ExitStatus);
  281. using (var reader = new StreamReader(command.OutputStream))
  282. {
  283. var lines = new List<string>();
  284. string line = null;
  285. while ((line = await reader.ReadLineAsync()) != null)
  286. {
  287. lines.Add(line);
  288. }
  289. Assert.AreEqual(6, lines.Count, string.Join("\n", lines));
  290. Assert.AreEqual(expectedResult, string.Join("\n", lines));
  291. }
  292. // We have already consumed OutputStream ourselves, so we expect Result to be empty.
  293. Assert.AreEqual("", command.Result);
  294. }
  295. }
  296. finally
  297. {
  298. RemoveFileOrDirectory(sshClient, remoteFile);
  299. }
  300. }
  301. }
  302. [TestMethod]
  303. public void Ssh_DynamicPortForwarding_DisposeSshClientWithoutStoppingPort()
  304. {
  305. const string searchText = "HTTP/1.1 301 Moved Permanently";
  306. const string hostName = "github.com";
  307. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  308. Socket socksSocket;
  309. using (var client = new SshClient(_connectionInfoFactory.Create()))
  310. {
  311. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  312. client.Connect();
  313. var forwardedPort = new ForwardedPortDynamic(1080);
  314. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  315. client.AddForwardedPort(forwardedPort);
  316. forwardedPort.Start();
  317. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  318. string.Empty,
  319. string.Empty);
  320. socksSocket = socksClient.Connect(hostName, 80);
  321. socksSocket.Send(httpGetRequest);
  322. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  323. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  324. }
  325. Assert.IsTrue(socksSocket.Connected);
  326. // check if client socket was properly closed
  327. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  328. }
  329. [TestMethod]
  330. public void Ssh_DynamicPortForwarding_DomainName()
  331. {
  332. const string searchText = "HTTP/1.1 301 Moved Permanently";
  333. const string hostName = "github.com";
  334. // Set-up a host alias for google.be on the remote server that is not known locally; this allows us to
  335. // verify whether the host name is resolved remotely.
  336. const string hostNameAlias = "dynamicportforwarding-test.for.sshnet";
  337. // Construct a HTTP request for which we expected the response to contain the search text.
  338. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  339. var ipAddresses = Dns.GetHostAddresses(hostName);
  340. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  341. try
  342. {
  343. using (var client = new SshClient(_connectionInfoFactory.Create()))
  344. {
  345. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  346. client.Connect();
  347. var forwardedPort = new ForwardedPortDynamic(1080);
  348. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  349. client.AddForwardedPort(forwardedPort);
  350. forwardedPort.Start();
  351. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  352. string.Empty,
  353. string.Empty);
  354. var socksSocket = socksClient.Connect(hostNameAlias, 80);
  355. socksSocket.Send(httpGetRequest);
  356. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  357. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  358. // Verify if port is still open
  359. socksSocket.Send(httpGetRequest);
  360. GetHttpResponse(socksSocket, Encoding.ASCII);
  361. forwardedPort.Stop();
  362. Assert.IsTrue(socksSocket.Connected);
  363. // check if client socket was properly closed
  364. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  365. forwardedPort.Start();
  366. // create new SOCKS connection and very whether the forwarded port is functional again
  367. socksSocket = socksClient.Connect(hostNameAlias, 80);
  368. socksSocket.Send(httpGetRequest);
  369. httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  370. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  371. forwardedPort.Dispose();
  372. Assert.IsTrue(socksSocket.Connected);
  373. // check if client socket was properly closed
  374. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  375. forwardedPort.Dispose();
  376. }
  377. }
  378. finally
  379. {
  380. if (hostsFileUpdated)
  381. {
  382. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  383. }
  384. }
  385. }
  386. [TestMethod]
  387. public void Ssh_DynamicPortForwarding_IPv4()
  388. {
  389. const string searchText = "HTTP/1.1 301 Moved Permanently";
  390. const string hostName = "github.com";
  391. var httpGetRequest = Encoding.ASCII.GetBytes($"GET /null HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  392. var ipv4 = Dns.GetHostAddresses(hostName).FirstOrDefault(p => p.AddressFamily == AddressFamily.InterNetwork);
  393. Assert.IsNotNull(ipv4, $@"No IPv4 address found for '{hostName}'.");
  394. using (var client = new SshClient(_connectionInfoFactory.Create()))
  395. {
  396. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  397. client.Connect();
  398. var forwardedPort = new ForwardedPortDynamic(1080);
  399. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  400. client.AddForwardedPort(forwardedPort);
  401. forwardedPort.Start();
  402. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  403. string.Empty,
  404. string.Empty);
  405. var socksSocket = socksClient.Connect(new IPEndPoint(ipv4, 80));
  406. socksSocket.Send(httpGetRequest);
  407. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  408. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  409. forwardedPort.Dispose();
  410. // check if client socket was properly closed
  411. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  412. }
  413. }
  414. /// <summary>
  415. /// Verifies whether channels are effectively closed.
  416. /// </summary>
  417. [TestMethod]
  418. public void Ssh_LocalPortForwardingCloseChannels()
  419. {
  420. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  421. const string hostName = "github.com";
  422. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  423. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  424. try
  425. {
  426. var connectionInfo = _connectionInfoFactory.Create();
  427. connectionInfo.MaxSessions = 1;
  428. using (var client = new SshClient(connectionInfo))
  429. {
  430. client.Connect();
  431. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  432. for (var i = 0; i < (connectionInfo.MaxSessions + 1); i++)
  433. {
  434. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  435. (uint)localEndPoint.Port,
  436. hostNameAlias,
  437. 80);
  438. client.AddForwardedPort(forwardedPort);
  439. forwardedPort.Start();
  440. try
  441. {
  442. using HttpClientHandler handler = new()
  443. {
  444. AllowAutoRedirect = false
  445. };
  446. using HttpClient httpClient = new(handler);
  447. using HttpResponseMessage httpResponse = httpClient.GetAsync("http://" + localEndPoint).Result;
  448. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  449. }
  450. finally
  451. {
  452. client.RemoveForwardedPort(forwardedPort);
  453. }
  454. }
  455. }
  456. }
  457. finally
  458. {
  459. if (hostsFileUpdated)
  460. {
  461. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  462. }
  463. }
  464. }
  465. [TestMethod]
  466. public void Ssh_LocalPortForwarding()
  467. {
  468. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  469. const string hostName = "github.com";
  470. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  471. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  472. try
  473. {
  474. using (var client = new SshClient(_connectionInfoFactory.Create()))
  475. {
  476. client.Connect();
  477. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  478. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  479. (uint)localEndPoint.Port,
  480. hostNameAlias,
  481. 80);
  482. forwardedPort.Exception +=
  483. (sender, args) => Console.WriteLine(@"ForwardedPort exception: " + args.Exception);
  484. client.AddForwardedPort(forwardedPort);
  485. forwardedPort.Start();
  486. try
  487. {
  488. using HttpClientHandler handler = new()
  489. {
  490. AllowAutoRedirect = false
  491. };
  492. using HttpClient httpClient = new(handler);
  493. using HttpResponseMessage httpResponse = httpClient.GetAsync("http://" + localEndPoint).Result;
  494. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  495. }
  496. finally
  497. {
  498. client.RemoveForwardedPort(forwardedPort);
  499. }
  500. }
  501. }
  502. finally
  503. {
  504. if (hostsFileUpdated)
  505. {
  506. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  507. }
  508. }
  509. }
  510. [TestMethod]
  511. public void Ssh_RemotePortForwarding()
  512. {
  513. var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
  514. var ipv4HostAddress = hostAddresses.First(p => p.AddressFamily == AddressFamily.InterNetwork);
  515. var endpoint1 = new IPEndPoint(ipv4HostAddress, 10000);
  516. var endpoint2 = new IPEndPoint(ipv4HostAddress, 10001);
  517. var areBytesReceivedOnListener1 = false;
  518. var areBytesReceivedOnListener2 = false;
  519. var bytesReceivedOnListener1 = new List<byte>();
  520. var bytesReceivedOnListener2 = new List<byte>();
  521. using (var socketListener1 = new AsyncSocketListener(endpoint1))
  522. using (var socketListener2 = new AsyncSocketListener(endpoint2))
  523. using (var bytesReceivedEventOnListener1 = new AutoResetEvent(false))
  524. using (var bytesReceivedEventOnListener2 = new AutoResetEvent(false))
  525. using (var client = new SshClient(_connectionInfoFactory.Create()))
  526. {
  527. socketListener1.BytesReceived += (received, socket) =>
  528. {
  529. bytesReceivedOnListener1.AddRange(received);
  530. bytesReceivedEventOnListener1.Set();
  531. };
  532. socketListener1.Start();
  533. socketListener2.BytesReceived += (received, socket) =>
  534. {
  535. bytesReceivedOnListener2.AddRange(received);
  536. bytesReceivedEventOnListener2.Set();
  537. };
  538. socketListener2.Start();
  539. client.Connect();
  540. var forwardedPort1 = new ForwardedPortRemote(IPAddress.Loopback,
  541. 10002,
  542. endpoint1.Address,
  543. (uint)endpoint1.Port);
  544. forwardedPort1.Exception += (sender, args) => Console.WriteLine(@"forwardedPort1 exception: " + args.Exception);
  545. client.AddForwardedPort(forwardedPort1);
  546. forwardedPort1.Start();
  547. var forwardedPort2 = new ForwardedPortRemote(IPAddress.Loopback,
  548. 10003,
  549. endpoint2.Address,
  550. (uint)endpoint2.Port);
  551. forwardedPort2.Exception += (sender, args) => Console.WriteLine(@"forwardedPort2 exception: " + args.Exception);
  552. client.AddForwardedPort(forwardedPort2);
  553. forwardedPort2.Start();
  554. using (var s = client.CreateShellStream("a", 80, 25, 800, 600, 200))
  555. {
  556. s.WriteLine($"telnet {forwardedPort1.BoundHost} {forwardedPort1.BoundPort}");
  557. s.Expect($"Connected to {forwardedPort1.BoundHost}\r\n");
  558. s.WriteLine("ABC");
  559. s.Flush();
  560. s.Expect("ABC");
  561. s.Close();
  562. }
  563. using (var s = client.CreateShellStream("b", 80, 25, 800, 600, 200))
  564. {
  565. s.WriteLine($"telnet {forwardedPort2.BoundHost} {forwardedPort2.BoundPort}");
  566. s.Expect($"Connected to {forwardedPort2.BoundHost}\r\n");
  567. s.WriteLine("DEF");
  568. s.Flush();
  569. s.Expect("DEF");
  570. s.Close();
  571. }
  572. areBytesReceivedOnListener1 = bytesReceivedEventOnListener1.WaitOne(1000);
  573. areBytesReceivedOnListener2 = bytesReceivedEventOnListener2.WaitOne(1000);
  574. forwardedPort1.Stop();
  575. forwardedPort2.Stop();
  576. }
  577. Assert.IsTrue(areBytesReceivedOnListener1);
  578. Assert.IsTrue(areBytesReceivedOnListener2);
  579. var textReceivedOnListener1 = Encoding.ASCII.GetString(bytesReceivedOnListener1.ToArray());
  580. Assert.AreEqual("ABC\r\n", textReceivedOnListener1);
  581. var textReceivedOnListener2 = Encoding.ASCII.GetString(bytesReceivedOnListener2.ToArray());
  582. Assert.AreEqual("DEF\r\n", textReceivedOnListener2);
  583. }
  584. /// <summary>
  585. /// Issue 1591
  586. /// </summary>
  587. [TestMethod]
  588. public void Ssh_ExecuteShellScript()
  589. {
  590. const string remoteFile = "/home/sshnet/run.sh";
  591. const string content = "#\bin\bash\necho Hello World!";
  592. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  593. {
  594. client.Connect();
  595. if (client.Exists(remoteFile))
  596. {
  597. client.DeleteFile(remoteFile);
  598. }
  599. using (var memoryStream = new MemoryStream())
  600. using (var sw = new StreamWriter(memoryStream, Encoding.ASCII))
  601. {
  602. sw.Write(content);
  603. sw.Flush();
  604. memoryStream.Position = 0;
  605. client.UploadFile(memoryStream, remoteFile);
  606. }
  607. }
  608. using (var client = new SshClient(_connectionInfoFactory.Create()))
  609. {
  610. client.Connect();
  611. try
  612. {
  613. var runChmod = client.RunCommand("chmod u+x " + remoteFile);
  614. runChmod.Execute();
  615. Assert.AreEqual(0, runChmod.ExitStatus, runChmod.Error);
  616. var runLs = client.RunCommand("ls " + remoteFile);
  617. var asyncResultLs = runLs.BeginExecute();
  618. var runScript = client.RunCommand(remoteFile);
  619. var asyncResultScript = runScript.BeginExecute();
  620. Assert.IsTrue(asyncResultScript.AsyncWaitHandle.WaitOne(10000));
  621. var resultScript = runScript.EndExecute(asyncResultScript);
  622. Assert.AreEqual("Hello World!\n", resultScript);
  623. Assert.IsTrue(asyncResultLs.AsyncWaitHandle.WaitOne(10000));
  624. var resultLs = runLs.EndExecute(asyncResultLs);
  625. Assert.AreEqual(remoteFile + "\n", resultLs);
  626. }
  627. finally
  628. {
  629. RemoveFileOrDirectory(client, remoteFile);
  630. }
  631. }
  632. }
  633. /// <summary>
  634. /// Verifies if a hosts file contains an entry for a given combination of IP address and hostname,
  635. /// and if necessary add either the host entry or an alias to an exist entry for the specified IP
  636. /// address.
  637. /// </summary>
  638. /// <param name="linuxAdminConnectionFactory"></param>
  639. /// <param name="ipAddress"></param>
  640. /// <param name="hostName"></param>
  641. /// <returns>
  642. /// <see langword="true"/> if an entry was added or updated in the specified hosts file; otherwise,
  643. /// <see langword="false"/>.
  644. /// </returns>
  645. private static bool AddOrUpdateHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  646. IPAddress ipAddress,
  647. string hostName)
  648. {
  649. const string hostsFile = "/etc/hosts";
  650. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  651. {
  652. client.Connect();
  653. var hostConfig = HostConfig.Read(client, hostsFile);
  654. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  655. if (hostEntry != null)
  656. {
  657. if (hostEntry.HostName == hostName)
  658. {
  659. return false;
  660. }
  661. foreach (var alias in hostEntry.Aliases)
  662. {
  663. if (alias == hostName)
  664. {
  665. return false;
  666. }
  667. }
  668. hostEntry.Aliases.Add(hostName);
  669. }
  670. else
  671. {
  672. bool mappingFound = false;
  673. for (var i = (hostConfig.Entries.Count - 1); i >= 0; i--)
  674. {
  675. hostEntry = hostConfig.Entries[i];
  676. if (hostEntry.HostName == hostName)
  677. {
  678. if (hostEntry.IPAddress.Equals(ipAddress))
  679. {
  680. mappingFound = true;
  681. continue;
  682. }
  683. // If hostname is currently mapped to another IP address, then remove the
  684. // current mapping
  685. hostConfig.Entries.RemoveAt(i);
  686. }
  687. else
  688. {
  689. for (var j = (hostEntry.Aliases.Count - 1); j >= 0; j--)
  690. {
  691. var alias = hostEntry.Aliases[j];
  692. if (alias == hostName)
  693. {
  694. hostEntry.Aliases.RemoveAt(j);
  695. }
  696. }
  697. }
  698. }
  699. if (!mappingFound)
  700. {
  701. hostEntry = new HostEntry(ipAddress, hostName);
  702. hostConfig.Entries.Add(hostEntry);
  703. }
  704. }
  705. hostConfig.Write(client, hostsFile);
  706. return true;
  707. }
  708. }
  709. /// <summary>
  710. /// Remove the mapping between a given IP address and host name from the remote hosts file either by
  711. /// removing a host entry entirely (if no other aliases are defined for the IP address) or removing
  712. /// the aliases that match the host name for the IP address.
  713. /// </summary>
  714. /// <param name="linuxAdminConnectionFactory"></param>
  715. /// <param name="ipAddress"></param>
  716. /// <param name="hostName"></param>
  717. /// <returns>
  718. /// <see langword="true"/> if the hosts file was updated; otherwise, <see langword="false"/>.
  719. /// </returns>
  720. private static bool RemoveHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  721. IPAddress ipAddress,
  722. string hostName)
  723. {
  724. const string hostsFile = "/etc/hosts";
  725. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  726. {
  727. client.Connect();
  728. var hostConfig = HostConfig.Read(client, hostsFile);
  729. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  730. if (hostEntry == null)
  731. {
  732. return false;
  733. }
  734. if (hostEntry.HostName == hostName)
  735. {
  736. if (hostEntry.Aliases.Count == 0)
  737. {
  738. hostConfig.Entries.Remove(hostEntry);
  739. }
  740. else
  741. {
  742. // Use one of the aliases (that are different from the specified host name) as host name
  743. // of the host entry.
  744. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  745. {
  746. var alias = hostEntry.Aliases[i];
  747. if (alias == hostName)
  748. {
  749. hostEntry.Aliases.RemoveAt(i);
  750. }
  751. else if (hostEntry.HostName == hostName)
  752. {
  753. // If we haven't already used one of the aliases as host name of the host entry
  754. // then do this now and remove the alias.
  755. hostEntry.HostName = alias;
  756. hostEntry.Aliases.RemoveAt(i);
  757. }
  758. }
  759. // If for some reason the host name of the host entry matched the specified host name
  760. // and it only had aliases that match the host name, then remove the host entry altogether.
  761. if (hostEntry.Aliases.Count == 0 && hostEntry.HostName == hostName)
  762. {
  763. hostConfig.Entries.Remove(hostEntry);
  764. }
  765. }
  766. }
  767. else
  768. {
  769. var aliasRemoved = false;
  770. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  771. {
  772. if (hostEntry.Aliases[i] == hostName)
  773. {
  774. hostEntry.Aliases.RemoveAt(i);
  775. aliasRemoved = true;
  776. }
  777. }
  778. if (!aliasRemoved)
  779. {
  780. return false;
  781. }
  782. }
  783. hostConfig.Write(client, hostsFile);
  784. return true;
  785. }
  786. }
  787. private static string GetHttpResponse(Socket socket, Encoding encoding)
  788. {
  789. var httpResponseBuffer = new byte[2048];
  790. // We expect:
  791. // * The response to contain the searchText in the first receive.
  792. // * The full response to be returned in the first receive.
  793. var bytesReceived = socket.Receive(httpResponseBuffer,
  794. 0,
  795. httpResponseBuffer.Length,
  796. SocketFlags.None);
  797. if (bytesReceived == 0)
  798. {
  799. return null;
  800. }
  801. if (bytesReceived == httpResponseBuffer.Length)
  802. {
  803. throw new Exception("We expect the HTTP response to be less than the buffer size. If not, we won't consume the full response.");
  804. }
  805. using (var sr = new StringReader(encoding.GetString(httpResponseBuffer, 0, bytesReceived)))
  806. {
  807. return sr.ReadToEnd();
  808. }
  809. }
  810. private static void CreateShellScript(IConnectionInfoFactory connectionInfoFactory, string remoteFile, string script)
  811. {
  812. using (var sftpClient = new SftpClient(connectionInfoFactory.Create()))
  813. {
  814. sftpClient.Connect();
  815. using (var sw = sftpClient.CreateText(remoteFile, new UTF8Encoding(false)))
  816. {
  817. sw.Write(script);
  818. }
  819. sftpClient.ChangePermissions(remoteFile, 0x1FF);
  820. }
  821. }
  822. private static void RemoveFileOrDirectory(SshClient client, string remoteFile)
  823. {
  824. using (var cmd = client.CreateCommand("rm -Rf " + remoteFile))
  825. {
  826. cmd.Execute();
  827. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  828. }
  829. }
  830. }
  831. }