2
0

SshTests.cs 41 KB

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