2
0

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_IntermittendOutput_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. /// <summary>
  198. /// Ignored for now, because:
  199. /// * OutputStream.Read(...) does not block when no data is available
  200. /// * SshCommand.(Begin)Execute consumes *OutputStream*, advancing its position.
  201. ///
  202. /// https://github.com/sshnet/SSH.NET/issues/650
  203. /// </summary>
  204. [TestMethod]
  205. [Ignore]
  206. public void Ssh_Command_IntermittendOutput_OutputStream()
  207. {
  208. const string remoteFile = "/home/sshnet/test.sh";
  209. var expectedResult = string.Join("\n",
  210. "Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  211. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  212. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  213. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  214. "Line 5 ",
  215. "Line 6");
  216. var scriptBuilder = new StringBuilder();
  217. scriptBuilder.Append("#!/bin/sh\n");
  218. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  219. scriptBuilder.Append("sleep .5\n");
  220. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  221. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  222. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  223. scriptBuilder.Append("sleep 2\n");
  224. scriptBuilder.Append("echo \"Line 5 \"\n");
  225. scriptBuilder.Append("echo Line 6 \n");
  226. scriptBuilder.Append("exit 13\n");
  227. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  228. {
  229. sshClient.Connect();
  230. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  231. try
  232. {
  233. using (var cmd = sshClient.CreateCommand("chmod 777 " + remoteFile))
  234. {
  235. cmd.Execute();
  236. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  237. }
  238. using (var command = sshClient.CreateCommand(remoteFile))
  239. {
  240. var asyncResult = command.BeginExecute();
  241. using (var reader = new StreamReader(command.OutputStream, new UTF8Encoding(false), false, 10))
  242. {
  243. var lines = new List<string>();
  244. string line = null;
  245. while ((line = reader.ReadLine()) != null)
  246. {
  247. lines.Add(line);
  248. }
  249. Assert.AreEqual(6, lines.Count, string.Join("\n", lines));
  250. Assert.AreEqual(expectedResult, string.Join("\n", lines));
  251. Assert.AreEqual(13, command.ExitStatus);
  252. }
  253. var actualResult = command.EndExecute(asyncResult);
  254. Assert.AreEqual(expectedResult, actualResult);
  255. Assert.AreEqual(expectedResult, command.Result);
  256. }
  257. }
  258. finally
  259. {
  260. RemoveFileOrDirectory(sshClient, remoteFile);
  261. }
  262. }
  263. }
  264. [TestMethod]
  265. public void Ssh_DynamicPortForwarding_DisposeSshClientWithoutStoppingPort()
  266. {
  267. const string searchText = "HTTP/1.1 301 Moved Permanently";
  268. const string hostName = "github.com";
  269. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  270. Socket socksSocket;
  271. using (var client = new SshClient(_connectionInfoFactory.Create()))
  272. {
  273. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  274. client.Connect();
  275. var forwardedPort = new ForwardedPortDynamic(1080);
  276. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  277. client.AddForwardedPort(forwardedPort);
  278. forwardedPort.Start();
  279. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  280. string.Empty,
  281. string.Empty);
  282. socksSocket = socksClient.Connect(hostName, 80);
  283. socksSocket.Send(httpGetRequest);
  284. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  285. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  286. }
  287. Assert.IsTrue(socksSocket.Connected);
  288. // check if client socket was properly closed
  289. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  290. }
  291. [TestMethod]
  292. public void Ssh_DynamicPortForwarding_DomainName()
  293. {
  294. const string searchText = "HTTP/1.1 301 Moved Permanently";
  295. const string hostName = "github.com";
  296. // Set-up a host alias for google.be on the remote server that is not known locally; this allows us to
  297. // verify whether the host name is resolved remotely.
  298. const string hostNameAlias = "dynamicportforwarding-test.for.sshnet";
  299. // Construct a HTTP request for which we expected the response to contain the search text.
  300. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  301. var ipAddresses = Dns.GetHostAddresses(hostName);
  302. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  303. try
  304. {
  305. using (var client = new SshClient(_connectionInfoFactory.Create()))
  306. {
  307. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  308. client.Connect();
  309. var forwardedPort = new ForwardedPortDynamic(1080);
  310. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  311. client.AddForwardedPort(forwardedPort);
  312. forwardedPort.Start();
  313. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  314. string.Empty,
  315. string.Empty);
  316. var socksSocket = socksClient.Connect(hostNameAlias, 80);
  317. socksSocket.Send(httpGetRequest);
  318. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  319. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  320. // Verify if port is still open
  321. socksSocket.Send(httpGetRequest);
  322. GetHttpResponse(socksSocket, Encoding.ASCII);
  323. forwardedPort.Stop();
  324. Assert.IsTrue(socksSocket.Connected);
  325. // check if client socket was properly closed
  326. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  327. forwardedPort.Start();
  328. // create new SOCKS connection and very whether the forwarded port is functional again
  329. socksSocket = socksClient.Connect(hostNameAlias, 80);
  330. socksSocket.Send(httpGetRequest);
  331. httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  332. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  333. forwardedPort.Dispose();
  334. Assert.IsTrue(socksSocket.Connected);
  335. // check if client socket was properly closed
  336. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  337. forwardedPort.Dispose();
  338. }
  339. }
  340. finally
  341. {
  342. if (hostsFileUpdated)
  343. {
  344. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  345. }
  346. }
  347. }
  348. [TestMethod]
  349. public void Ssh_DynamicPortForwarding_IPv4()
  350. {
  351. const string searchText = "HTTP/1.1 301 Moved Permanently";
  352. const string hostName = "github.com";
  353. var httpGetRequest = Encoding.ASCII.GetBytes($"GET /null HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  354. var ipv4 = Dns.GetHostAddresses(hostName).FirstOrDefault(p => p.AddressFamily == AddressFamily.InterNetwork);
  355. Assert.IsNotNull(ipv4, $@"No IPv4 address found for '{hostName}'.");
  356. using (var client = new SshClient(_connectionInfoFactory.Create()))
  357. {
  358. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  359. client.Connect();
  360. var forwardedPort = new ForwardedPortDynamic(1080);
  361. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  362. client.AddForwardedPort(forwardedPort);
  363. forwardedPort.Start();
  364. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  365. string.Empty,
  366. string.Empty);
  367. var socksSocket = socksClient.Connect(new IPEndPoint(ipv4, 80));
  368. socksSocket.Send(httpGetRequest);
  369. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  370. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  371. forwardedPort.Dispose();
  372. // check if client socket was properly closed
  373. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  374. }
  375. }
  376. /// <summary>
  377. /// Verifies whether channels are effectively closed.
  378. /// </summary>
  379. [TestMethod]
  380. public void Ssh_LocalPortForwardingCloseChannels()
  381. {
  382. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  383. const string hostName = "github.com";
  384. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  385. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  386. try
  387. {
  388. var connectionInfo = _connectionInfoFactory.Create();
  389. connectionInfo.MaxSessions = 1;
  390. using (var client = new SshClient(connectionInfo))
  391. {
  392. client.Connect();
  393. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  394. for (var i = 0; i < (connectionInfo.MaxSessions + 1); i++)
  395. {
  396. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  397. (uint)localEndPoint.Port,
  398. hostNameAlias,
  399. 80);
  400. client.AddForwardedPort(forwardedPort);
  401. forwardedPort.Start();
  402. try
  403. {
  404. var httpRequest = (HttpWebRequest) WebRequest.Create("http://" + localEndPoint);
  405. httpRequest.Host = hostName;
  406. httpRequest.Method = "GET";
  407. httpRequest.AllowAutoRedirect = false;
  408. try
  409. {
  410. using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
  411. {
  412. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  413. }
  414. }
  415. catch (WebException ex)
  416. {
  417. Assert.AreEqual(WebExceptionStatus.ProtocolError, ex.Status);
  418. Assert.IsNotNull(ex.Response);
  419. using (var httpResponse = ex.Response as HttpWebResponse)
  420. {
  421. Assert.IsNotNull(httpResponse);
  422. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  423. }
  424. }
  425. }
  426. finally
  427. {
  428. client.RemoveForwardedPort(forwardedPort);
  429. }
  430. }
  431. }
  432. }
  433. finally
  434. {
  435. if (hostsFileUpdated)
  436. {
  437. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  438. }
  439. }
  440. }
  441. [TestMethod]
  442. public void Ssh_LocalPortForwarding()
  443. {
  444. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  445. const string hostName = "github.com";
  446. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  447. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  448. try
  449. {
  450. using (var client = new SshClient(_connectionInfoFactory.Create()))
  451. {
  452. client.Connect();
  453. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  454. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  455. (uint)localEndPoint.Port,
  456. hostNameAlias,
  457. 80);
  458. forwardedPort.Exception +=
  459. (sender, args) => Console.WriteLine(@"ForwardedPort exception: " + args.Exception);
  460. client.AddForwardedPort(forwardedPort);
  461. forwardedPort.Start();
  462. try
  463. {
  464. var httpRequest = (HttpWebRequest) WebRequest.Create("http://" + localEndPoint);
  465. httpRequest.Host = hostName;
  466. httpRequest.Method = "GET";
  467. httpRequest.Accept = "text/html";
  468. httpRequest.AllowAutoRedirect = false;
  469. try
  470. {
  471. using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
  472. {
  473. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  474. }
  475. }
  476. catch (WebException ex)
  477. {
  478. Assert.AreEqual(WebExceptionStatus.ProtocolError, ex.Status);
  479. Assert.IsNotNull(ex.Response);
  480. using (var httpResponse = ex.Response as HttpWebResponse)
  481. {
  482. Assert.IsNotNull(httpResponse);
  483. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  484. }
  485. }
  486. }
  487. finally
  488. {
  489. client.RemoveForwardedPort(forwardedPort);
  490. }
  491. }
  492. }
  493. finally
  494. {
  495. if (hostsFileUpdated)
  496. {
  497. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  498. }
  499. }
  500. }
  501. [TestMethod]
  502. public void Ssh_RemotePortForwarding()
  503. {
  504. var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
  505. var ipv4HostAddress = hostAddresses.First(p => p.AddressFamily == AddressFamily.InterNetwork);
  506. var endpoint1 = new IPEndPoint(ipv4HostAddress, 10000);
  507. var endpoint2 = new IPEndPoint(ipv4HostAddress, 10001);
  508. var bytesReceivedOnListener1 = new List<byte>();
  509. var bytesReceivedOnListener2 = new List<byte>();
  510. using (var socketListener1 = new AsyncSocketListener(endpoint1))
  511. using (var socketListener2 = new AsyncSocketListener(endpoint2))
  512. using (var client = new SshClient(_connectionInfoFactory.Create()))
  513. {
  514. socketListener1.BytesReceived += (received, socket) => bytesReceivedOnListener1.AddRange(received);
  515. socketListener1.Start();
  516. socketListener2.BytesReceived += (received, socket) => bytesReceivedOnListener2.AddRange(received);
  517. socketListener2.Start();
  518. client.Connect();
  519. var forwardedPort1 = new ForwardedPortRemote(IPAddress.Loopback,
  520. 10002,
  521. endpoint1.Address,
  522. (uint)endpoint1.Port);
  523. forwardedPort1.Exception += (sender, args) => Console.WriteLine(@"forwardedPort1 exception: " + args.Exception);
  524. client.AddForwardedPort(forwardedPort1);
  525. forwardedPort1.Start();
  526. var forwardedPort2 = new ForwardedPortRemote(IPAddress.Loopback,
  527. 10003,
  528. endpoint2.Address,
  529. (uint)endpoint2.Port);
  530. forwardedPort2.Exception += (sender, args) => Console.WriteLine(@"forwardedPort2 exception: " + args.Exception);
  531. client.AddForwardedPort(forwardedPort2);
  532. forwardedPort2.Start();
  533. using (var s = client.CreateShellStream("a", 80, 25, 800, 600, 200))
  534. {
  535. s.WriteLine($"telnet {forwardedPort1.BoundHost} {forwardedPort1.BoundPort}");
  536. s.Expect($"Connected to {forwardedPort1.BoundHost}\r\n");
  537. s.WriteLine("ABC");
  538. s.Flush();
  539. s.Expect("ABC");
  540. s.Close();
  541. }
  542. using (var s = client.CreateShellStream("b", 80, 25, 800, 600, 200))
  543. {
  544. s.WriteLine($"telnet {forwardedPort2.BoundHost} {forwardedPort2.BoundPort}");
  545. s.Expect($"Connected to {forwardedPort2.BoundHost}\r\n");
  546. s.WriteLine("DEF");
  547. s.Flush();
  548. s.Expect("DEF");
  549. s.Close();
  550. }
  551. forwardedPort1.Stop();
  552. forwardedPort2.Stop();
  553. }
  554. var textReceivedOnListener1 = Encoding.ASCII.GetString(bytesReceivedOnListener1.ToArray());
  555. Assert.AreEqual("ABC\r\n", textReceivedOnListener1);
  556. var textReceivedOnListener2 = Encoding.ASCII.GetString(bytesReceivedOnListener2.ToArray());
  557. Assert.AreEqual("DEF\r\n", textReceivedOnListener2);
  558. }
  559. /// <summary>
  560. /// Issue 1591
  561. /// </summary>
  562. [TestMethod]
  563. public void Ssh_ExecuteShellScript()
  564. {
  565. const string remoteFile = "/home/sshnet/run.sh";
  566. const string content = "#\bin\bash\necho Hello World!";
  567. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  568. {
  569. client.Connect();
  570. if (client.Exists(remoteFile))
  571. {
  572. client.DeleteFile(remoteFile);
  573. }
  574. using (var memoryStream = new MemoryStream())
  575. using (var sw = new StreamWriter(memoryStream, Encoding.ASCII))
  576. {
  577. sw.Write(content);
  578. sw.Flush();
  579. memoryStream.Position = 0;
  580. client.UploadFile(memoryStream, remoteFile);
  581. }
  582. }
  583. using (var client = new SshClient(_connectionInfoFactory.Create()))
  584. {
  585. client.Connect();
  586. try
  587. {
  588. var runChmod = client.RunCommand("chmod u+x " + remoteFile);
  589. runChmod.Execute();
  590. Assert.AreEqual(0, runChmod.ExitStatus, runChmod.Error);
  591. var runLs = client.RunCommand("ls " + remoteFile);
  592. var asyncResultLs = runLs.BeginExecute();
  593. var runScript = client.RunCommand(remoteFile);
  594. var asyncResultScript = runScript.BeginExecute();
  595. Assert.IsTrue(asyncResultScript.AsyncWaitHandle.WaitOne(10000));
  596. var resultScript = runScript.EndExecute(asyncResultScript);
  597. Assert.AreEqual("Hello World!\n", resultScript);
  598. Assert.IsTrue(asyncResultLs.AsyncWaitHandle.WaitOne(10000));
  599. var resultLs = runLs.EndExecute(asyncResultLs);
  600. Assert.AreEqual(remoteFile + "\n", resultLs);
  601. }
  602. finally
  603. {
  604. RemoveFileOrDirectory(client, remoteFile);
  605. }
  606. }
  607. }
  608. /// <summary>
  609. /// Verifies if a hosts file contains an entry for a given combination of IP address and hostname,
  610. /// and if necessary add either the host entry or an alias to an exist entry for the specified IP
  611. /// address.
  612. /// </summary>
  613. /// <param name="linuxAdminConnectionFactory"></param>
  614. /// <param name="ipAddress"></param>
  615. /// <param name="hostName"></param>
  616. /// <returns>
  617. /// <see langword="true"/> if an entry was added or updated in the specified hosts file; otherwise,
  618. /// <see langword="false"/>.
  619. /// </returns>
  620. private static bool AddOrUpdateHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  621. IPAddress ipAddress,
  622. string hostName)
  623. {
  624. const string hostsFile = "/etc/hosts";
  625. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  626. {
  627. client.Connect();
  628. var hostConfig = HostConfig.Read(client, hostsFile);
  629. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  630. if (hostEntry != null)
  631. {
  632. if (hostEntry.HostName == hostName)
  633. {
  634. return false;
  635. }
  636. foreach (var alias in hostEntry.Aliases)
  637. {
  638. if (alias == hostName)
  639. {
  640. return false;
  641. }
  642. }
  643. hostEntry.Aliases.Add(hostName);
  644. }
  645. else
  646. {
  647. bool mappingFound = false;
  648. for (var i = (hostConfig.Entries.Count - 1); i >= 0; i--)
  649. {
  650. hostEntry = hostConfig.Entries[i];
  651. if (hostEntry.HostName == hostName)
  652. {
  653. if (hostEntry.IPAddress.Equals(ipAddress))
  654. {
  655. mappingFound = true;
  656. continue;
  657. }
  658. // If hostname is currently mapped to another IP address, then remove the
  659. // current mapping
  660. hostConfig.Entries.RemoveAt(i);
  661. }
  662. else
  663. {
  664. for (var j = (hostEntry.Aliases.Count - 1); j >= 0; j--)
  665. {
  666. var alias = hostEntry.Aliases[j];
  667. if (alias == hostName)
  668. {
  669. hostEntry.Aliases.RemoveAt(j);
  670. }
  671. }
  672. }
  673. }
  674. if (!mappingFound)
  675. {
  676. hostEntry = new HostEntry(ipAddress, hostName);
  677. hostConfig.Entries.Add(hostEntry);
  678. }
  679. }
  680. hostConfig.Write(client, hostsFile);
  681. return true;
  682. }
  683. }
  684. /// <summary>
  685. /// Remove the mapping between a given IP address and host name from the remote hosts file either by
  686. /// removing a host entry entirely (if no other aliases are defined for the IP address) or removing
  687. /// the aliases that match the host name for the IP address.
  688. /// </summary>
  689. /// <param name="linuxAdminConnectionFactory"></param>
  690. /// <param name="ipAddress"></param>
  691. /// <param name="hostName"></param>
  692. /// <returns>
  693. /// <see langword="true"/> if the hosts file was updated; otherwise, <see langword="false"/>.
  694. /// </returns>
  695. private static bool RemoveHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  696. IPAddress ipAddress,
  697. string hostName)
  698. {
  699. const string hostsFile = "/etc/hosts";
  700. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  701. {
  702. client.Connect();
  703. var hostConfig = HostConfig.Read(client, hostsFile);
  704. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  705. if (hostEntry == null)
  706. {
  707. return false;
  708. }
  709. if (hostEntry.HostName == hostName)
  710. {
  711. if (hostEntry.Aliases.Count == 0)
  712. {
  713. hostConfig.Entries.Remove(hostEntry);
  714. }
  715. else
  716. {
  717. // Use one of the aliases (that are different from the specified host name) as host name
  718. // of the host entry.
  719. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  720. {
  721. var alias = hostEntry.Aliases[i];
  722. if (alias == hostName)
  723. {
  724. hostEntry.Aliases.RemoveAt(i);
  725. }
  726. else if (hostEntry.HostName == hostName)
  727. {
  728. // If we haven't already used one of the aliases as host name of the host entry
  729. // then do this now and remove the alias.
  730. hostEntry.HostName = alias;
  731. hostEntry.Aliases.RemoveAt(i);
  732. }
  733. }
  734. // If for some reason the host name of the host entry matched the specified host name
  735. // and it only had aliases that match the host name, then remove the host entry altogether.
  736. if (hostEntry.Aliases.Count == 0 && hostEntry.HostName == hostName)
  737. {
  738. hostConfig.Entries.Remove(hostEntry);
  739. }
  740. }
  741. }
  742. else
  743. {
  744. var aliasRemoved = false;
  745. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  746. {
  747. if (hostEntry.Aliases[i] == hostName)
  748. {
  749. hostEntry.Aliases.RemoveAt(i);
  750. aliasRemoved = true;
  751. }
  752. }
  753. if (!aliasRemoved)
  754. {
  755. return false;
  756. }
  757. }
  758. hostConfig.Write(client, hostsFile);
  759. return true;
  760. }
  761. }
  762. private static string GetHttpResponse(Socket socket, Encoding encoding)
  763. {
  764. var httpResponseBuffer = new byte[2048];
  765. // We expect:
  766. // * The response to contain the searchText in the first receive.
  767. // * The full response to be returned in the first receive.
  768. var bytesReceived = socket.Receive(httpResponseBuffer,
  769. 0,
  770. httpResponseBuffer.Length,
  771. SocketFlags.None);
  772. if (bytesReceived == 0)
  773. {
  774. return null;
  775. }
  776. if (bytesReceived == httpResponseBuffer.Length)
  777. {
  778. throw new Exception("We expect the HTTP response to be less than the buffer size. If not, we won't consume the full response.");
  779. }
  780. using (var sr = new StringReader(encoding.GetString(httpResponseBuffer, 0, bytesReceived)))
  781. {
  782. return sr.ReadToEnd();
  783. }
  784. }
  785. private static void CreateShellScript(IConnectionInfoFactory connectionInfoFactory, string remoteFile, string script)
  786. {
  787. using (var sftpClient = new SftpClient(connectionInfoFactory.Create()))
  788. {
  789. sftpClient.Connect();
  790. using (var sw = sftpClient.CreateText(remoteFile, new UTF8Encoding(false)))
  791. {
  792. sw.Write(script);
  793. }
  794. sftpClient.ChangePermissions(remoteFile, 0x1FF);
  795. }
  796. }
  797. private static void RemoveFileOrDirectory(SshClient client, string remoteFile)
  798. {
  799. using (var cmd = client.CreateCommand("rm -Rf " + remoteFile))
  800. {
  801. cmd.Execute();
  802. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  803. }
  804. }
  805. }
  806. }