SshTests.cs 41 KB

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